3. Longest Substring Without Repeating Characters

Medium
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

属于滑动窗口那种Two Pointers的题, 维持l, r两个指针,每次遇到没有出现过的字符,就加入到set里面,并且向右扩展窗口;遇到出现过的字符,就要缩小窗口,从左边开始删除,知道删完这个重复的元素,那么这时候set里面就没有该元素了,又可以进行新的窗口扩展。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0){
            return 0;
        }
        int l = 0;
        int r = 0;
        int maxLen = 0;
        HashSet<Character> set = new HashSet<>();
        while (r < s.length() && l < s.length()){
            if (!set.contains(s.charAt(r))){
                set.add(s.charAt(r));
                maxLen = Math.max(maxLen, r - l + 1);
                r++;
            } else {
                set.remove(s.charAt(l));
                l++;
            }
        }
        return maxLen;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容