Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
## Sliding Window(set)による解法 ★
---
### 1回目 (3m20s)
時間計算量: O(N)<br>
空間計算量: 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)<br>
空間計算量: 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
Comment on lines +40 to +44
Copy link
Copy Markdown

@thonda28 thonda28 Jun 1, 2024

Choose a reason for hiding this comment

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

dict を使うのであれば、value に index を指定してみてはどうでしょうか?今の実装だと value が 0 または 1 で実質 bool のように扱っているので、コメントにあるように dict を使う旨味がなさそうです。(また 0 または 1 しか入らないにも関わらず int 型なのも少し違和感があります。)

{s[right]: right} として value に index を持たせる実装にすると、while 文を使わずに left を更新できるので少しは旨味がありそうです。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

すみません、ご指摘の通り、この実装はindexを記録できていないですね。
かなり意味ないことをしておりました。書き直します。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

アドバイスを基に書き直しました。

max_length = max(max_length, right - left + 1)

return max_length
```

## dictを使った解法 (indexを記録)
---
時間計算量: O(N)<br>
空間計算量: O(N)
```python
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left = 0
letter_to_index = defaultdict(int)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これはdict()で良さそうです。

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
```