1. 題目
給定一個字符串 s ,找出 至多 包含兩個不同字符的最長子串 t ,並返回該子串的長度。
示例 1:
輸入: "eceba"
輸出: 3
解釋: t 是 "ece",長度爲3。
示例 2:
輸入: "ccaabbb"
輸出: 5
解釋: t 是 "aabbb",長度爲5。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2. 解題
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s) {
int k = 2, i = 0, j = 0, maxlen = 0;
unordered_map<char, int> m;
while(j < s.size())
{
if(m.size() <= k)
++m[s[j++]];
while(m.size()>k)
{
if(--m[s[i]] == 0)
m.erase(s[i]);
i++;
}
maxlen = max(maxlen, j-i);
}
return maxlen;
}
};
24 ms 7.9 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公衆號(Michael阿明),一起加油、一起學習進步!