C++ solution , not the best but easy to understand


  • 0
    G
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            
            map<char,int> hash;
            int maxLen = 0,curIndex = 0;
            int i = 0;
            while(i < s.length())
            {
                if(hash.find(s[i]) == hash.end())
                {
                    hash[s[i]] = i;
                }
                else
                {
                    if(hash[s[i]] >= curIndex)
                        curIndex = hash[s[i]] + 1;
                        
                    hash[s[i]] = i;
    
                }
                
                 if(maxLen < (i - curIndex + 1))
                        maxLen = (i - curIndex + 1);
                    i++;
            }
            return maxLen;
        }
    };

Log in to reply
 

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