From 7fdee204e712f43ec064c51a712bfc07f310f8f4 Mon Sep 17 00:00:00 2001 From: potrue <126231160+potrue@users.noreply.github.com> Date: Sat, 16 Aug 2025 22:18:44 +0900 Subject: [PATCH] 3. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ --- 3/3.md | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 3/3.md diff --git a/3/3.md b/3/3.md new file mode 100644 index 0000000..28357e9 --- /dev/null +++ b/3/3.md @@ -0,0 +1,58 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + int lengthOfLongestSubstring(string s) { + int substring_start = 0; + int max_substring_length = 0; + unordered_map character_to_index; + for (int i = 0; i < s.size(); ++i) { + char c = s[i]; + if (character_to_index.contains(c)) { + int current_c_pos = character_to_index[c]; + for (int j = substring_start; j <= current_c_pos; ++j) { + character_to_index.erase(s[j]); + } + substring_start = current_c_pos + 1; + } + character_to_index[c] = i; + max_substring_length = max(max_substring_length, i - substring_start + 1); + } + return max_substring_length; + } +}; +``` + +## 他の人のコードを見てみる + +https://github.com/tokuhirat/LeetCode/pull/48/files +https://github.com/huyfififi/coding-challenges/pull/29/files +https://github.com/ryosuketc/leetcode_arai60/pull/37/files +`substring_start`の更新式を`substring_start = max(substring_start, current_c_pos + 1)`のような感じにすることで辞書をわざわざ変える必要がなくなる。なるほど。 +https://github.com/Ryotaro25/leetcode_first60/pull/52/files +c++のcharは内部でASCIIコードの整数型として扱われているので、`vector letter_to_count(128, 0)`みたいなものに対して`letter_to_count['a']`みたいなことができるらしい。aからzまでのASCIIコードは10進数で97から122だそう。 + +## 最終コード + +using_characters.size()をintにキャストせずにそのままmaxに渡すと、max関数にintとsize_t(leetcodeの環境ではunsigned longみたいです)が渡されることになって(少なくともleetcodeの環境上では)エラーになってしまいました。 + +``` +class Solution { +public: + int lengthOfLongestSubstring(string s) { + unordered_set using_characters; + int max_length = 0; + int start = 0; + for (int end = 0; end < s.size(); ++end) { + while (using_characters.contains(s[end])) { + using_characters.erase(s[start]); + ++start; + } + using_characters.emplace(s[end]); + max_length = max(max_length, (int)using_characters.size()); + } + return max_length; + } +}; +```