Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.2 kB
0
Indexable
Never
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int i=0;
        int res=0;
        unordered_set<char> set;
        for(int j=0;j<s.size();j++){
            while(set.find(s[j])!=set.end()){ //until we encounter a new character, keep deleting
                set.erase(s[i]);
                i++;
            }
            //all redundant characters are deleted, all unique characters in set now
            set.insert(s[j]); //new character , keep adding into set
            res=max(res,j-i+1);
        }
        return res;
    }
};



/* class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int i=0,j=0;
        unordered_set<char>set;
        int res=0;
        
        while(j<s.size()){
            if(set.find(s[j]) == set.end()){
                set.insert(s[j]); //new character
                j++;
                res=max(res,j-i);
            }else{ //char prev exists in the set
                set.erase(s[i]); //i needs to be eerased until i reaches the repeating character that is newly encountered
                i++;
            }
        }
        return res;
    }
};
 */