[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 向右滑动,扩大窗口,此时窗口内的字符串一个无重复子字符串。

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

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    if(s.size()<=1) return s.size();    
    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;
    }
};

方法2

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int len=s.size();
        int ans=0;
        int tmp2=0;//开始点
        map<char,int> hash;
        for(int i=0;i<=len-1;i++)
        {
            if(hash.count(s[i])!=0&&(hash[s[i]]+1)>tmp2)
                tmp2=hash[s[i]]+1;
            if(i-tmp2+1>ans)
                ans=i-tmp2+1;
            hash[s[i]]=i;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/momo_mo520/article/details/80183008
今日推荐