JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • 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)){
                // WAABCWD 此时会发生currHead比map.get(s.charAt(w))+1大的情况
                // index 0 1 2 3 4 5 6
                //       W A A B C W D
                // 当currHead在位置2,i在位置5时,发现了重复
                // 但是这时currHead的位置比
                // map.get('W') + 1  = 1要大,此时不能取0,
                // 而是要让currHead保持当前的位置
                // 总结起来就是currHead只能增加不能减少
                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:
        map = {}
        res = start = 0
        for index, c in enumerate(s):
            if c in map:
                start = max(map[c] + 1, start)

            res = max(res, index - start + 1)
            map[c] = index

        return res