美文网首页
算法----无重复字符的最长子串

算法----无重复字符的最长子串

作者: 咕哒咕 | 来源:发表于2021-02-25 10:08 被阅读0次

相关标签:哈希

eg.

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

解法:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int res = 0;
        Set<Character> set = new HashSet<>();
        for(int l = 0, r = 0; r < s.length(); r++) {
            char c = s.charAt(r);
            while(set.contains(c)) {
                set.remove(s.charAt(l++));
            }
            set.add(c);
            res = Math.max(res, set.size());
        }

        return res;
    }
}

相关文章

网友评论

      本文标题:算法----无重复字符的最长子串

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