xinyu04

导航

LeetCode 3 Longest Substring Without Repeating Characters

Given a string s, find the length of the longest substring without repeating characters.

Solution

求最长的不重复子串。我们利用左右两个指针来模拟端点,然后用 \(set\) 来记录出现过的字符。当出现重复的字符时, 我们需要回退到上一个出现该字符的位置, 用 \(set.erase()\)即可

点击查看代码
class Solution {
private:
    int l,r;
    int ans = 1;
    set<char> S;
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.length();
        if(s=="")return 0;
        if(n==1)return 1;
        l=0;
        for(r=0;r<n;r++){
            if(S.find(s[r])==S.end()){
                S.insert(s[r]);ans=max(ans,r-l+1);
            }
            else{
                // remove
                while(l!=r && s[l]!=s[r]){
                    S.erase(s[l]);l++;
                }
                S.erase(s[l]);l++;
                S.insert(s[r]);
                ans=max(ans,r-l+1);
            }
        }
        return ans;
    }
};

posted on 2022-07-20 15:43  Blackzxy  阅读(13)  评论(0编辑  收藏  举报