LeetCode第3题 无重复字符的最长子串

思路:
滑动窗口。start和end分别表示滑动窗口的开头和结尾,表示一个没有重复字符的子串。用map记录已经访问过的字符的位置。滑动的方式是以end逐渐靠近结尾。并在过程中维护start的值。当end访问到重复字符时更新start。注意,这里start和end都只能变大,不能变小。

换个角度,其实滑动窗口表示的是以end结尾的最长的最长子串。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s == null) {
            return 0;
        }
        int start = 0,end = 0,ans = 0;
        HashMap<Character,Integer> map = new HashMap<>();
        for(;end < s.length(); end++) {
            if(map.containsKey(s.charAt(end))) {
                start = Math.max(map.get(s.charAt(end)) + 1,start);
            }
            map.put(s.charAt(end),end);
            ans = Math.max(ans,end - start + 1);
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/vxzhg/article/details/104263895