O(n) and one pass C++ solution, can you do better? I doubt it.


  • -1
    Y
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int n = s.size();
            if (n <= 1) return n;
            unordered_map<char,int> m;
            int curlen = 0, start = 0, maxlen = 0;
            //curlen is the max length of substring contains s[i], 
            //start is where the current substring starts, maxlen is the max 
            //length of substring, which becomes bigger when curlen is bigger. 
            for (int i = 0; i < n; i++) {
                char c = s[i];
                auto k = m.find(c);
                if (k == m.end()) {
                    //in this case, k is a new element, so curlen++;
                    curlen++;
                    m[c] = i;
                }
                else {
                    if (k->second >= start) {
                        //in this case, there is duplicate for current substring, so we
                        //need increase the first index of current substring. 
                        start = k->second+1;
                        curlen = i - start +1;
                        m[c] = i;
                    }
                    else {
                        curlen++;
                        m[c] = i;
                    }
                }
                maxlen = max(maxlen,curlen);
            }
            return maxlen;
        }
    };

Log in to reply
 

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