Longest Substring Without Repeating Characters

Jin Shang bio photo By Jin Shang

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Solution:

Two pointers

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.empty()) return 0;
        int ans=0;
        set<char> ex; //exist
        int a=0,b=0; //a: begin of substr, b: end of substr(included)
        while(b<s.size()){
            if(ex.find(s[b])!=ex.end()){//exist
                while(s[a]!=s[b]){
                    ex.erase(s[a]);
                    a++;
                }
                a++;
            }
            ex.insert(s[b]);
            ans = max(ans, b-a+1);
            b++;
        }
        return ans;
        
    }
};