My accepted c++ solution


  • 3
    D
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            unordered_map<char, int> hash;
            int maxlen = 0;
            int index = 0;
            
            for (int i = 0; i < s.size(); i++)
            {
                
                if(hash.find(s[i]) != hash.end())
                {
                    if (maxlen < hash.size()) 
                    {
                        maxlen = hash.size();
                    }
                    index = hash[s[i]];
                    for (auto it = hash.begin(); it != hash.end();)
                    {
                        if (it->second <= index)
                        {
                            it = hash.erase(it);
                        }else{
                            it++;
                        }
                    }
                }
                 
                hash[s[i]] = i;
            }
            if (maxlen < hash.size()) maxlen = hash.size();
            
            return maxlen;
        }
    };

  • 0
    T

    This solution is smart and simple!


Log in to reply
 

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