Wednesday, June 22, 2016

The Longest Substring without repeating characters -- LeetCode

[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]
Assume T[i] is the length of longest sub-string, without repeating characters, ending at i, T[0] = 1.
T[i+1]  = min(  T[i]+1,     //when s[i+1] does not appear in last T[i] characters,
                          the distance between the previous appearance of s[i+1] and s[i+1] );

When scanning through, use a map to track the last appearance (index) of each character. The time complexity is O(N).

[Solution]
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.size()<2) return s.size();
       
        int len =0;
        vector<int> t(s.size(), 0);
        unordered_map<char, int> c_map;
        t[0] = 1;
        c_map[s[0]] = 0;
       
        for (int i=1; i<s.size(); i++) {
            int dist = (c_map.find(s[i])!=c_map.end())? i-c_map[s[i]] : 0;
            c_map[s[i]] = i;
           
            if (dist==0) t[i]=t[i-1] +1;
            else
                t[i] = min (dist, t[i-1]+1);
               
            len = max (len, t[i]);
        }

        return len;
    }
};

No comments:

Post a Comment