Simple O(N) solution using unordered_set


  • 0
    X
    int lengthOfLongestSubstring(string s) {
            if(s.length() == 0) return 0;
            int mLen= 0;
            int j=0;
            int i=0;
            unordered_set<char> unique_set;
            while(i < s.length()){
                while(j < s.length()){
                    if(unique_set.find(s[j])  == unique_set.end() ){
                        unique_set.insert(s[j++]);
                    }else break;
                }
                mLen = max(mLen,j-i);
                unique_set.erase(s[i++]);
            }
            return mLen;
        }

Log in to reply
 

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