My C++ solution, 55ms


  • 1
    J
    int lengthOfLongestSubstring(string s) {
        if(s.size()<2){
            return s.size();
        }
    
        int longest=0;
        int tempCount=0;
        unordered_set<char> keys;
        auto beginindexIt =s.begin();
        auto it = beginindexIt; 
        while(it!=s.end()){
            if(s.end()-it+tempCount <=longest){
                return longest;
            }
            if(keys.find(*it) == keys.end()){
                keys.insert(*it);
    			tempCount++;
    			if(tempCount>longest){
    				longest = tempCount;
    			}
            }else{
               for(beginindexIt;beginindexIt<it;beginindexIt++){
    			   if(*beginindexIt!=*it){
    				   keys.erase(*beginindexIt);
    				   tempCount--;
    			   }else{
    				   beginindexIt++;
    				   break;
    			   }
               }
            }
            it++;
        }
        return longest;
    }

Log in to reply
 

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