[LeetCode] 3. Longest Substring Without Repeating Characters 解题思路

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

问题:找到字符串中最长的无重复字符的子字符串。

这题是求最长连续子字符串,可以使用 滑动窗口算法(Slide Window Algorithm)求解,和 Minimum Size Subarray Sum 相似。

设下标 l 和 r, 把左开右闭 [l, r) 想象成一个窗口。

  • 当 s[r] 和窗口内字符重复时, 则 l 向右滑动,缩小窗口。
  • 当s[r] 和窗口内字符不重复时,则 r 向右滑动,扩大窗口,此时窗口内的字符串一个无重复子字符串。

在所有的无重复子字符串中,找到长度最大的,即为原问题解。

int lengthOfLongestSubstring(string s) {
    
    int l = 0;
    int r = 1;
    
    unordered_set<int> setv;
    setv.insert(s[l]);
    
    int longest = 1;
    
    while (r < s.size()) {
        
        if (setv.count(s[r]) != 0) {
            setv.erase(s[l]);
            l++;
        }else{
            setv.insert(s[r]);
            r++;
            longest = max(longest, (int)setv.size());
        }
    }
    
    return longest;
}
原文地址:https://www.cnblogs.com/TonyYPZhang/p/5061202.html