水下功夫做透,水上才能顺风顺水。

无重复字符的最长子串-滑动窗口法

class Solution {
    public int lengthOfLongestSubstring(String s) {

        int len = s.length(), max = 0;
        //key是字符,value是字符位置
        Map<Character, Integer> map = new HashMap<>();
     
        int start = 0;//右指针
        for (int end = 0; end <len; end++) {//end 是左指针
            //当左指针遇到重复字符,并记录1次当前最长值。(右指针跨过前1个重复的字符后作为起始)
            if (map.containsKey(s.charAt(end))) {
                //已经被跨过的重复字符不算重复。(右指针只往前走,不往后退。)
                start = Math.max(map.get(s.charAt(end))+1,start);
            }
            int curLen = end-start+1;
            if(curLen>max){
               max = curLen;
            }
            map.put(s.charAt(end), end);
        }
        return max;
    }
}

 

posted @ 2022-02-26 22:28  北方寒士  阅读(46)  评论(0)    收藏  举报