Wednesday, September 24, 2014

[Leetcode] Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
Analysis:
If there are duplicate characters closed to current position than j, the substring without repeating characters should start from pos+1

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

No comments:

Post a Comment