Leetcode|滑动窗口变种|3. 无重复字符的最长子串

2021-09-22 11:23:37 浏览数 (1)

1 滑动窗口变种

代码语言:javascript复制
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.size() < 2) return s.size();
        unordered_map<char, int> need;
        int left = 0, right = 0;
        int len = 0;
        while (right < s.size()) {
            char in = s[right];
            right  ;
            need[in]  ;
            // 左侧窗口缩,当右侧扩展元素存在窗口内,则停止右侧扩展,开始左侧紧缩窗口
            while (need[in] > 1) {
                char out = s[left];
                left  ;
                need[out]--;
            }
            len = max(right - left, len);
        }
        return len;
    }
};

0 人点赞