Monday, November 25, 2013

LeetCode Problem : Longest Substring Without Repeating Characters

Problem

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.

Code

int lengthOfLongestSubstring(string s) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = s.size();
    if(n < 2)
        return n;
    int max_a = 1;
    vector<int> M(n,1);
    for(int i = 1;i < n; ++i){
        for(int j = i - 1;j >= i - M[i - 1]; --j){
            if(s[i] != s[j]){
                ++M[i];
                if(max_a < M[i])
                    max_a = M[i];
            }
            else
                break;
        }
    }
    return max_a;
}

No comments:

Post a Comment