C++ solution with two running pointers and an unordered set


  • 0
    M
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int len = s.length();
            if(len == 0) return 0;
            
            int mx = 0, i = 0;
            unordered_set<char> st;
            for(int j = 0; j < len; ++j){
                if(!st.count(s[j])){
                    st.insert(s[j]);
                    mx = max(mx, (int)st.size());
                }else{
                    while(i < j && st.count(s[j])){
                        st.erase(s[i++]);
                    }
                    st.insert(s[j]);
                    mx = max(mx, j - i + 1);
                }
            }
            return mx;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.