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

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

同向双指针问题,利用hashmap判重

class Solution {
    int res;
    public int lengthOfLongestSubstring(String s) {
        Map<Character,Integer> map = new HashMap<>();
        char[] strs=s.toCharArray();
        for(int i=0,j=0;i<strs.length;i++)
        {
            map.compute(strs[i],(k,v) -> v==null ? 1:v+1);
            while(map.get(strs[i]) > 1) // 判断是否有重复,重复元素只能是新加入的strs[i]发生重复
            {
                map.compute(strs[j],(k,v)-> v-1);
                j++; //缩小范围
            }
            res=Math.max(res,i-j+1);
        }
        return res;
    }
}

 

posted @ 2024-10-06 00:22  风乐  阅读(12)  评论(0)    收藏  举报