diff --git a/arai60/longest-substring-without-repeating-characters/step1.py b/arai60/longest-substring-without-repeating-characters/step1.py new file mode 100644 index 0000000..9f5d447 --- /dev/null +++ b/arai60/longest-substring-without-repeating-characters/step1.py @@ -0,0 +1,24 @@ +""" +出現した文字を集合で管理して判定するとよさそう +連続でなければならないのに気づいていなかった。サンプルを最初にちゃんと確認しなければ。 +連続ならば、すでに出現したものが現れたときにリセットすればよい +いや、被りが来た時点で、被りの次のindexから始めることにしないといけない +辞書で管理するほうが良いか +if seen.get(s[i]) andというような条件にしてしまっていて、seen.get(s[i]) == 0の場合が弾かれてしまっていたのに気づくのに時間がかかってしまった... + +経過時間:22m +""" + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + seen = dict() + answer = 0 + start_index = 0 + for i in range(len(s)): + if s[i] in seen and seen.get(s[i]) >= start_index: + answer = max(answer, i-start_index) + start_index = seen.get(s[i])+1 + seen[s[i]] = i + answer = max(answer, len(s)-start_index) + + return answer diff --git a/arai60/longest-substring-without-repeating-characters/step2.py b/arai60/longest-substring-without-repeating-characters/step2.py new file mode 100644 index 0000000..3215427 --- /dev/null +++ b/arai60/longest-substring-without-repeating-characters/step2.py @@ -0,0 +1,21 @@ +""" +算術をスペース入れずにやってしまう癖を直す +start_index → left +enumerateを使う +answerに代入する処理の位置を変える + +char_to_indexのほうがよさそう +""" + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + char_to_index = dict() + answer = 0 + left = 0 + for right, c in enumerate(s): + if c in char_to_index and char_to_index[c] >= left: + left = char_to_index[c] + 1 + char_to_index[c] = right + answer = max(answer, right - left + 1) + + return answer diff --git a/arai60/longest-substring-without-repeating-characters/step3.py b/arai60/longest-substring-without-repeating-characters/step3.py new file mode 100644 index 0000000..bf2384c --- /dev/null +++ b/arai60/longest-substring-without-repeating-characters/step3.py @@ -0,0 +1,17 @@ +""" +1回目: 3m55s + +""" + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + seen = dict() + answer = 0 + left = 0 + for right, c in enumerate(s): + if c in seen and seen[c] >= left: + left = seen[c] + 1 + seen[c] = right + answer = max(answer, right - left + 1) + + return answer diff --git a/arai60/longest-substring-without-repeating-characters/step4.py b/arai60/longest-substring-without-repeating-characters/step4.py new file mode 100644 index 0000000..384a9ec --- /dev/null +++ b/arai60/longest-substring-without-repeating-characters/step4.py @@ -0,0 +1,16 @@ +""" +returnの前の改行をなくす +answer → max_length +""" + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + char_to_index = dict() + max_length = 0 + left = 0 + for right, c in enumerate(s): + if c in char_to_index and char_to_index[c] >= left: + left = char_to_index[c] + 1 + char_to_index[c] = right + max_length = max(max_length, right - left + 1) + return max_length