Longest Substring Without Repeating Characters ---- LeetCode 003

Posted on 2016-03-30 14:45  徐岩  阅读(98)  评论(0)    收藏  举报

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.

class Solution 
{
public:
    int lengthOfLongestSubstring(string s) 
    {
        int len = s.length();
        bool exist[maxn] = {false};
        int maxLen = 0;
        
        int i = 0, j = 0;
        while(j < len)
        {
            if(exist[s[j]])
            {
                maxLen = max(maxLen, j - i);
                while(s[i] != s[j])
                {
                    exist[s[i]] = false;
                    ++i;
                }
                ++i;
                ++j;
            }
            else
            {
                exist[s[j]] = true;
                ++j;
            }
        }
        maxLen = max(maxLen, len - i);
        return maxLen;
    }
private:
    const int maxn = 256;
};
View Code