Tuesday, December 2, 2014

Longest Substring Without Repeating Characters

       int lengthOfLongestSubstring(string s) {
        int n=s.length();
        int i=0,j=0,maxLen=0;
        bool exist[256]={false};
        while(j<n){
            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++;
            }
        }
        return max(maxLen,n-i);
    }
 //same idea, more concise
 int lengthOfLongestSubstring(string s) {
           bool exist[256]={false};
        int res = 0;
        int start = 0, end = 0, N = s.size();
        while (end < N && start + res < N)
        {
            if (!exist[s[end]])
                exist[s[end++]] = true;
            else
                exist[s[start++]] = false;
            res = max(end - start, res);
        }
        return res;    
    }

No comments:

Post a Comment