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

传送门

代码

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<>();
        int ans = 0,n = s.length();
        for(int r = -1,l = 0;l < n; ++l) {
            if(l != 0) {
                set.remove(s.charAt(l - 1));
            }
            while(r + 1 < n && !set.contains(s.charAt(r + 1))) {
                set.add(s.charAt(r + 1));
                r ++;
            }
            ans = Math.max(ans,r - l + 1);
        }
        return ans;
    }
}

思路

双指针 \(O(n)\)
用 HashSet 来做去重
每次循环 左指针向右走一步,同时把 HashSet 中对应的元素删除
同时,让 右边指针 一直向右走,走到不能走为止(指针越界 或者 HashSet 已经包含了相同元素)
每次都更新一边 ans 的值即可

posted @ 2020-12-14 12:51  lukelmouse  阅读(46)  评论(0编辑  收藏  举报