Loading

3. 无重复字符的最长子串

https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

使用滑动窗口,max会一直更新结束之前的最长的长度,

在最初的时候每一次遇到一个键,都会添加到map,后面如果遇到重复的,就会把走过的相同键的最靠右的位置+1作为新的left

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0) return 0;
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0, left = 0;
        for(int i = 0;i < s.length(); i++){
            if(map.containsKey(s.charAt(i))){
                left = Math.max(left, map.get(s.charAt(i)) + 1);
            }
			map中的键不能重复,新的键会覆盖掉以前的老键
        map.put(s.charAt(i), i);
        max = Math.max(max, i - left + 1);
        }
        return max;
    }
}
posted @ 2021-11-19 19:17  Zhbeii  阅读(26)  评论(0编辑  收藏  举报