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.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.length()==0)
            return 0;
            
        int start=0;
        int max=0;
        int index[256];
        for(int i=0;i<256;i++)
            index[i]=-1;
        int strlength=s.length();
        for(int i=0;i<strlength;i++)
        {
            //not repeat
            if(index[s[i]]==-1)
            {
                index[s[i]]=i;
                if(i-start+1>max) max++;
            }
            //repeat
            else
            {
                //clear hash
                while(start<=index[s[i]])
                {
                    index[s[start]]=-1;
                    start++;
                }
                index[s[i]]=i;
            }
        }
        return max;
    }
};
posted @ 2014-05-29 15:03  erictanghu  阅读(100)  评论(0编辑  收藏  举报