[Sliding window] Jianzhi Offer 48. The longest substring without repeated characters

Please find the longest substring that does not contain repeated characters from the string, and calculate the length of the longest substring.

Example 1:

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

Example 2:

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

Example 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

hint:

s.length <= 40000

answer:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        // 滑动窗口
        int p = 0; 
        int q = 0;
        int maxLen = 0; // 最大长度
        Set<Character> set = new HashSet<>(); // 保存当前窗口中的字符
        // 右指针
        while (q < s.length()) {
            char c = s.charAt(q);
            if (!set.contains(c)) { // 如果不包含,q++,maxLen = q-p
                set.add(c);
                q++;
                if ((q-p) > maxLen) {
                    maxLen = q-p;
                }
                continue;
            }
            // 如果包含,那么移动p指针到重复的位置
            if (set.contains(c)) {
                while (set.contains(c)) {
                    set.remove(s.charAt(p));
                    p++;
                }
            }
        }
        return maxLen;
    }
}

Guess you like

Origin blog.csdn.net/wjavadog/article/details/126443478