Sunday, February 15, 2015

LeetCode [159] Longest Substring with At Most Two Distinct Characters

159. Longest Substring with At Most Two Distinct Characters
Medium

Given a string s , find the length of the longest substring t  that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int n = s.size(), i = 0, j = 0, maxLen = 0;
        map<char, int> mp;
        while(j<n){
            mp[s[j]]++;
            while(mp.size()>2){
                if(--mp[s[i]]==0){
                    mp.erase(s[i]);
                }
                i++;
            }
            if(j-i+1>maxLen) maxLen = j-i+1;
            j++;
        }
        return maxLen;
    }
};

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        int n = s.size(), ndiff = 0, l = 0, r = 0, len = 0;
        vector<int> hash(128, 0);
        while(r<n){
            int c = s[r++];
            hash[c]++;
            if(hash[c]==1){
                ndiff++;
                while(ndiff>2){
                    int c1 = s[l++];
                    hash[c1]--;
                    if(hash[c1]==0) ndiff--;
                }
            }
            len = max(len, r-l);
        }
        return len;
    }
};

No comments:

Post a Comment