美文网首页LeeCode
力扣百题-3. 无重复字符的最长子串

力扣百题-3. 无重复字符的最长子串

作者: 康大侠 | 来源:发表于2021-02-07 10:05 被阅读0次
3. 无重复字符的最长子串.png

LeeCode官方题解

利用滑动窗口,for(int right = 0; right < s.length(); right++)这里是在不断的调整窗口的右边,根据HashMap判断右边的元素是否出现过,不断调整左边的位置,计算最长长度,时间复杂度O(n),空间复杂度O(n)

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;
        int max = 0;
        int left = 0;
        HashMap<Character,Integer> map = new HashMap<>();
       // 更新右边距
        for(int right = 0; right < s.length(); right++) {
            if(map.containsKey(s.charAt(right))) {
       // 更新左边距
                left = Math.max(left,map.get(s.charAt(right)) + 1);
            }
            map.put(s.charAt(right),right);
            max = Math.max(max,right - left + 1);
        }
        return max;
    }
}

相关文章

网友评论

    本文标题:力扣百题-3. 无重复字符的最长子串

    本文链接:https://www.haomeiwen.com/subject/ictztltx.html