My short C++ solution


  • 3
    J
    int lengthOfLongestSubstring(string s) {
    	unordered_map<char, int> hmap;
    	int startPos = 0, maxLength = 0;
    	
    	for (int i = 0; i<s.length(); i++) {
    		if (hmap.find(s[i]) != hmap.end())
    			startPos = max(hmap.find(s[i])->second + 1, startPos);
    		hmap[s[i]] = i;
    		maxLength = max(maxLength, i - startPos + 1);
    	}
    	
    	return maxLength;
    }

  • 0
    N

    Your code is very concise and work good. But I am not so clear about the startPos.
    Could you explain your idea ?


  • 0
    J

    The variable, startPos, is simply the start position of the substring. You can understand my code with simple example. Let's say we have a string "abcdca". Before 2nd 'c', we got 4 as a maximum length of substring. If we are at 2nd 'c', the start position is changed to the next position of 1st 'c'. However, if we are at the 2nd 'a' startPos should not be changed because the first 'a' is preceded than the first 'c'.


  • 0
    N

    Thanks a lot! It make sense!


  • 0
    M

    I am relatively new to c++, could you please explain what does the below line of your code does?
    I am sure your are trying to see for a duplicate character but how does end() function does that?

    hmap.find(s[i]) != hmap.end()


  • 0
    M

    I figured that out!


Log in to reply
 

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