Simple 12ms C++ solution


  • 0
    S

    The idea is to use a vector as a hashmap, and two pointers (left and i) to indicate the length of the current substring.

    class Solution {
    public:
    	int lengthOfLongestSubstring(string s) {
    		int left = 0, max = 0;
    		vector<int> map(128, -1);
    		for (int i = 0; i < s.size();) {
    			unsigned char ch = s[i];
    			int index = map[ch];
    			if (index++ != -1)
    				left = left > index ? left : index;
    			map[ch] = i++;
    			max = max > i - left? max : i - left;
    		}
    		return max;
    	}
    };
    

Log in to reply
 

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