Monday, April 27, 2015

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.
Show Tags


Solution:
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> char_set;
        int start = 0, size = s.size();
        int result = 0, max_result = 0;
        
        for (int i = 0; i < size; i++) {
            if (char_set.find(s[i]) != char_set.end()) {
                while (start <= char_set[s[i]])
                    char_set.erase(s[start++]); // clear all before the dup.
            }
            char_set[s[i]] = i;
            max_result = max(max_result, i - start + 1);
        }
        return max_result;
       
    }
};

Complexity: O(2n)

========== Optimized version =====
 new complexity is O(n).

class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 0) {
return 0;
}
int left = 0;
int ans = 0;
unordered_map<char, int> mp;
for (int right = 0; right < s.size(); right++) {
if (mp.count(s[right])) {
// This loop can be removed.
/**
while (left <= mp[s[right]]) {
mp.erase(s[left]);
left++;
}
*/
left = max(left, mp[s[right]] + 1);
}
mp[s[right]] = right;
ans = max(ans, right - left + 1);
}
return ans;
}
};

No comments:

Post a Comment