Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions arai60/longest-substring-without-repeating-characters/step1.py
Original file line number Diff line number Diff line change
@@ -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
Comment on lines +19 to +20
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(単純に忘れただけだと思いますが)+-の両脇にスペースを入れた方が良いと思います。

seen[s[i]] = i
answer = max(answer, len(s)-start_index)

return answer
21 changes: 21 additions & 0 deletions arai60/longest-substring-without-repeating-characters/step2.py
Original file line number Diff line number Diff line change
@@ -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
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

max_lengthの方が分かりやすいかもしれないです。

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
17 changes: 17 additions & 0 deletions arai60/longest-substring-without-repeating-characters/step3.py
Original file line number Diff line number Diff line change
@@ -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
16 changes: 16 additions & 0 deletions arai60/longest-substring-without-repeating-characters/step4.py
Original file line number Diff line number Diff line change
@@ -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