Monday, June 10, 2013

Leetcode: Longest Substring Without Repeating Characters in C++


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.
Solution:
int lengthOfLongestSubstring(string s) {
        vector<int> curmap(256,-1);
        int n = s.size();
        int curlen = 0;
        int maxlen = 0;
        int curstart = 0;
        for(int i=0;i<n;i++)
        {
            int current = curmap[s[i]];
            if(current==-1)
            {
               curmap[s[i]] = i;
               curlen++;
               if(maxlen<curlen)
                 maxlen = curlen;
            }
            else
            {
                while(curstart<=current)
                {
                    curmap[s[curstart]] = -1;
                    curstart++;
                }
                curlen = i-current;
                curmap[s[i]] = i;
            }
            
        }
        return maxlen;
    }

No comments:

Post a Comment