# Leetcode 筆記 :(3) Longest Substring Without Repeating Characters
###### tags: `Leetcode`
## 題目
Given a string `s`, find the length of the **longest substring** without repeating characters.
**Example 1:**
```
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
```
***Example 2:***
```
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
```
***Example 3:***
```
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
```
***Example 4:***
```
Input: s = ""
Output: 0
```
## 嘗試
1. while 後面接上 else ,這在迴圈條件為假的時候執行。
2. 使用Sliding Window
## Code
```python=
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
sub_str = ''
max_len = 0
for i in s:
while i in sub_str:
sub_str = sub_str[1:]
else:
sub_str += i
max_len = max(len(sub_str), max_len)
return max_len
```
PTT 上找到的解答
```python=
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
indices, j, ans = {}, 0, 0
for i, c in enumerate(s):
if c in indices:
j = max(indices[c] + 1, j)
ans = max(ans, i - j + 1)
indices[c] = i
return ans
```