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 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;
    }
}

你可能感兴趣的:(3. Longest Substring Without Repeating Characters)