• ㊗️
• 大家
• offer
• 多多！

## Problem

Given a string, 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.


Constraints:

• $0 <= s.length <= 5 * 10^4$
• s consists of English letters, digits, symbols and spaces.

## Code

class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int maxLen = 0;

int j = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
// index 0 1 2 3 4 5 6
//       W A A B C W D
// map.get('W') + 1  = 1要大，此时不能取0，
j = Math.max(j, map.get(c) + 1);
}

maxLen = Math.max(maxLen, i - j + 1);
map.put(c, i);
}

return maxLen;
}
}

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
start = res = 0
hm = {}
for i, c in enumerate(s):
if c in hm:
start = max(start, hm[c] + 1)  # 不能往回走
res = max(res, i - start + 1)
hm[c] = i
return res