diff --git "a/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/3. Longest Substring Without Repeating Characters.md" "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/3. Longest Substring Without Repeating Characters.md" new file mode 100644 index 0000000..0420e9d --- /dev/null +++ "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/3. Longest Substring Without Repeating Characters.md" @@ -0,0 +1,69 @@ +## Sliding Window(set)による解法 ★ +--- +### 1回目 (3m20s) +時間計算量: O(N)
+空間計算量: O(N) + +```python +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + left = 0 + max_length = 0 + letters_in_windows = set() + + for right in range(len(s)): + while s[right] in letters_in_windows: + letters_in_windows.discard(s[left]) + left += 1 + + letters_in_windows.add(s[right]) + + max_length = max(max_length, right - left + 1) + + return max_length +``` + +## dictを使った解法 +--- +時間計算量: O(N)
+空間計算量: O(N) + +(あまり旨みはない。indexが必要な時に便利か。) +```python +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + left = 0 + letter_to_index = defaultdict(int) + max_length = 0 + + for right in range(len(s)): + while letter_to_index[s[right]] > 0: + letter_to_index[s[left]] -= 1 + left += 1 + + letter_to_index[s[right]] += 1 + max_length = max(max_length, right - left + 1) + + return max_length +``` + +## dictを使った解法 (indexを記録) +--- +時間計算量: O(N)
+空間計算量: O(N) +```python +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + left = 0 + letter_to_index = defaultdict(int) + max_length = 0 + + for right in range(len(s)): + if s[right] in letter_to_index and left <= letter_to_index[s[right]]: + left = letter_to_index[s[right]] + 1 + + letter_to_index[s[right]] = right + max_length = max(max_length, right - left + 1) + + return max_length +```