diff --git a/3.Longest-Substring-Without-Repeating-Characters/__pycache__/sol2.cpython-310.pyc b/3.Longest-Substring-Without-Repeating-Characters/__pycache__/sol2.cpython-310.pyc new file mode 100644 index 0000000..ffd6f1d Binary files /dev/null and b/3.Longest-Substring-Without-Repeating-Characters/__pycache__/sol2.cpython-310.pyc differ diff --git a/3.Longest-Substring-Without-Repeating-Characters/memo.md b/3.Longest-Substring-Without-Repeating-Characters/memo.md new file mode 100644 index 0000000..12c692c --- /dev/null +++ b/3.Longest-Substring-Without-Repeating-Characters/memo.md @@ -0,0 +1,24 @@ +# 3. Longest Substring Without Repeating Characters + +- sol1.py: 自力で解いたが、テストの途中を print するなどデバッグして答えを合わせた + +コメント集 +- https://github.com/olsen-blue/Arai60/pull/49#discussion_r2005295464 +> seen_char_to_index.get(s[right], -1) と使えば、条件分岐を回避できますね。 + + + +知らなかった(勉強したことはある気がする)が、初期の実装がこのアルゴリズムになっていた +- 尺取法 + - https://qiita.com/drken/items/ecd1a472d3a0e7db8dce +- sliding window + - https://qiita.com/rumblekat03/items/4edd9dd4607280c994d1 + + +https://github.com/mamo3gr/arai60/blob/3_longest-substring-without-repeating-characters/3_longest-substring-without-repeating-characters/memo.md + +> char_to_index.get(c, -1) として条件分岐をなくす (step2). コードとしてはすっきりするけど、読み手からしたらシミュレートの手間が増えそう。 + +という考えもあるのか。 + +sol2.py: 他の人のコードとコメントを参考にもう一度書き直す diff --git a/3.Longest-Substring-Without-Repeating-Characters/sol1.py b/3.Longest-Substring-Without-Repeating-Characters/sol1.py new file mode 100644 index 0000000..ebff081 --- /dev/null +++ b/3.Longest-Substring-Without-Repeating-Characters/sol1.py @@ -0,0 +1,21 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + if not s: + return 0 + seen_char_to_idx = {} + start = 0 + max_length = 0 + last = start + 1 + seen_char_to_idx[s[start]] = start + while start < len(s): + while last < len(s) and s[last] not in seen_char_to_idx: + seen_char_to_idx[s[last]] = last + last += 1 + max_length = max(max_length, last - start) + if last >= len(s): + break + start = max(seen_char_to_idx[s[last]] + 1, start) + seen_char_to_idx[s[last]] = last + last += 1 + + return max_length diff --git a/3.Longest-Substring-Without-Repeating-Characters/sol2.py b/3.Longest-Substring-Without-Repeating-Characters/sol2.py new file mode 100644 index 0000000..b5b0fc9 --- /dev/null +++ b/3.Longest-Substring-Without-Repeating-Characters/sol2.py @@ -0,0 +1,12 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + last_index = {} + start = 0 + max_length = 0 + for end, ch in enumerate(s): + prev = last_index.get(ch, -1) + if prev >= start: + start = prev + 1 + last_index[ch] = end + max_length = max(max_length, end - start + 1) + return max_length