Wednesday, May 15, 2013

Longest Sub-string without repeating characters

[Question]
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.

[Analysis]
Dynamic programming. Define L(i) as, the longest sub-string without repeating characters and ending at index i. Go each L(i) and find the maximum L(i).

[Solution]
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.empty()) return 0;
     
        int* count = new int[s.size()];
        int max_len;
        unordered_map<char, int> char_last_index;
     
        char_last_index[s[0]] = 0;
        max_len = count[0]=1;
        for (int i=1; i<s.size(); i++) {
            if (s[i-1]==s[i]) {
                count[i] = 1;
            }
            else {
                if ( char_last_index.find(s[i]) != char_last_index.end() ){
                    count[i] = min( count[i-1]+1, i-char_last_index[s[i]] );
                }
                else {
                    count[i] = count[i-1]+1;
                }
            }
            char_last_index[s[i]] = i;
            if (count[i]>max_len) {
                max_len = count[i];
            }
        }
        delete count;
        return max_len;
    }
};

No comments:

Post a Comment