My solution in 10 lines, short and simple


  • 1
    P
    int lengthOfLongestSubstring(string s) {
            map<char, int> charMap;
            int maxLen = 0,lastIndex = -1;
            for (int i = 0; i < s.size(); i++)
            {
                if (charMap.find(s[i]) != charMap.end() && lastIndex < charMap[s[i]])
                        lastIndex = charMap[s[i]];
                maxLen = max(maxLen,i - lastIndex);
                charMap[s[i]] = i;
            }
            return maxLen;
        }
    

    Above is my code :)


  • -1
    T

    Thank you for sharing! Nicest solution so far!

    Here is my java version:

        public int lengthOfLongestSubstring(String s) {
        int[] index = new int[256];
        int last = 0, max = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (index[ch] > last)
                last = index[ch];
            max = Math.max(max, i - last + 1);
            index[ch] = i + 1;
        }
    
        return max;
    }

  • 0
    L

    map is overkill, an array of 256 is sufficient.


  • 0
    P

    Yes, nice improvement. If s contains only a small set of characters, using a map is better than a fix-size array.


Log in to reply
 

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