159. Longest Substring with At Most Two Distinct Characters
給定一個字符串 s,返回最多包含兩個不同字符的最長子字符串的長度。
範例 :
輸入:s = "eceba" 輸出:3 解釋:該子字符串是 "ece",其長度為 3。
Python
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
if not s:
return 0
# Initialize pointers and a dictionary to store character counts
left = 0
right = 0
char_count = {}
max_len = 0
while right < len(s):
char_count[s[right]] = char_count.get(s[right], 0) + 1
right += 1
while len(char_count) > 2:
char_count[s[left]] -= 1
if char_count[s[left]] == 0:
del char_count[s[left]]
left += 1
max_len = max(max_len, right - left)
return max_len
17.17MB, 249ms
C++
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
if (s.empty()) {
return 0;
}
unordered_map<char, int> char_count;
int left = 0, right = 0, max_len = 0;
while (right < s.length()) {
char_count[s[right]]++;
right++;
while (char_count.size() > 2) {
char_count[s[left]]--;
if (char_count[s[left]] == 0) {
char_count.erase(s[left]);
}
left++;
}
max_len = max(max_len, right - left);
}
return max_len;
}
};
37.08MB, 160ms
Javascript
/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstringTwoDistinct = function(s) {
if (s.length === 0) return 0;
let left = 0, right = 0, maxLen = 0;
const charCount = new Map();
while (right < s.length) {
// Add the character at right pointer to the map
charCount.set(s[right], (charCount.get(s[right]) || 0) + 1);
right++;
// If there are more than 2 distinct characters, move the left pointer
while (charCount.size > 2) {
charCount.set(s[left], charCount.get(s[left]) - 1);
if (charCount.get(s[left]) === 0) {
charCount.delete(s[left]);
}
left++;
}
// Update the maximum length of the substring
maxLen = Math.max(maxLen, right - left);
}
return maxLen;
};
57.66MB, 125ms