Given a string S, find the length of the longest substring T that contains at most two distinct characters.
For example,
Given S = "eceba",
T is "ece" which its length is 3.
給一個字符串,找出最多有兩個不同字符的最長子串。還是滑動窗口法,定義一個HashMap或者Array來存儲出現過的字符個數,左右指針初始位子為0,右指針向右掃,掃到新字符不同字符數加1,存入HashMap,掃到出現過的字符,HashMap對應字符數量加1。如果不同字符數大於2了,就把左指針位置的字符在HashMap中的數量減1,注意不一定是這一個,如果此時這個字符的數量大於0,說明還有這個字符存在,左指針加1繼續右移,掃到的字符以后不會在窗口里了,要在HashMap中減1,如果這個字符減1后為0了,說明這個字符在窗口中沒有了,此時不同字符數就可減1,左指針在右移1位指向下一個字符,統計此時窗口長度與最大長度比較,保留最大值。重復上面步驟,直到右指針掃完所有字符。最后返回最大長度。
Java: T: O(n), S: O(1)
public int lengthOfLongestSubstringTwoDistinct(String s) {
int max=0;
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
int start=0;
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
map.put(c, map.get(c)+1);
}else{
map.put(c,1);
}
if(map.size()>2){
max = Math.max(max, i-start);
while(map.size()>2){
char t = s.charAt(start);
int count = map.get(t);
if(count>1){
map.put(t, count-1);
}else{
map.remove(t);
}
start++;
}
}
}
max = Math.max(max, s.length()-start);
return max;
}
Java:
public int lengthOfLongestSubstringTwoDistinct(String s) {
Map<Character, Integer> map = new HashMap<>();
int start = 0, end = 0;
int counter = 0, len = 0;
while(end < s.length()){
char cur = s.charAt(end);
if(!map.containsKey(cur)) map.put(cur, 0);
map.put(cur, map.get(cur) + 1);
if(map.get(cur) == 1) counter++;//new distinct char
while(counter > 2){//
char c2 = s.charAt(start);
map.put(c2, map.get(c2) - 1);
if(map.get(c2) == 0) counter--;
start++;
}
len = Math.max(end - start + 1, len);
end++;
}
return len;
}
Python:
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s):
longest, start, distinct_count, visited = 0, 0, 0, [0 for _ in xrange(256)]
for i, char in enumerate(s):
if visited[ord(char)] == 0:
distinct_count += 1
visited[ord(char)] += 1
while distinct_count > 2:
visited[ord(s[start])] -= 1
if visited[ord(s[start])] == 0:
distinct_count -= 1
start += 1
longest = max(longest, i - start + 1)
return longest
C++:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int res = 0, left = 0;
unordered_map<char, int> m;
for (int i = 0; i < s.size(); ++i) {
++m[s[i]];
while (m.size() > 2) {
if (--m[s[left]] == 0) m.erase(s[left]);
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
類似題目:
[LeetCode] 3.Longest Substring Without Repeating Characters 最長無重復子串
[LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K個不同字符的最長子串
All LeetCode Questions List 題目匯總
