1. 程式人生 > 其它 >至多包含兩個不同字元的最長子串

至多包含兩個不同字元的最長子串

leetcode 159. 至多包含兩個不同字元的最長子串

159. 至多包含兩個不同字元的最長子串

給定一個字串s,找出至多包含兩個不同字元的最長子串t,並返回該子串的長度。

示例 1:

輸入: "eceba"
輸出: 3
解釋: t 是 "ece",長度為3。

示例 2:

輸入: "ccaabbb"
輸出: 5
解釋: t是 "aabbb",長度為5。
 1 #include <iostream>
 2 #include <unordered_map>
 3 
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int lengthOfLongestSubstringTwoDistinct(string
s) { 9 unordered_map<char, int> hashMap; 10 unsigned int left = 0; 11 unsigned int right = 0; 12 unsigned int maxSubstringTwoDistinctLen = 0; 13 unsigned int &maxLen = maxSubstringTwoDistinctLen; // 變數型別過長,起個別名 14 for (; right < s.size(); right++) {
15 hashMap[s[right]]++; 16 // 滑動左指標處理子串中包含不同字元個數超過2個情況 17 for (; hashMap.size() > 2; left++) { 18 // 如果該字元出現次數超過1個,滑動左指標時只需要減少該字元出現的次數 19 if (hashMap[s[left]] > 1) { 20 hashMap[s[left]]--; 21 } else
if (hashMap[s[left]] == 1) { // 如果該字元直出現一次,則從子串中刪除該字元 22 hashMap.erase(s[left]); 23 } 24 } 25 // 子串中最多隻包含2個不同字元時,子串最大長度為左右指標的間隔長度 26 maxLen = std::max(maxLen, right - left + 1); 27 } 28 return maxLen; 29 } 30 }; 31 int main() 32 { 33 Solution *test = new Solution(); 34 string s = "abcabcbb"; 35 std::cout << "s: " << s << endl; 36 std::cout << "maxSubstringTwoDistinctLen:"<< test->lengthOfLongestSubstringTwoDistinct(s) << endl; // 4 37 38 s = ""; 39 std::cout << "s: " << s << endl; 40 std::cout << "maxSubstringTwoDistinctLen:"<< test->lengthOfLongestSubstringTwoDistinct(s) << endl; // 0 41 42 s = "bbbb"; 43 std::cout << "s: " << s << endl; 44 std::cout << "maxSubstringTwoDistinctLen:"<< test->lengthOfLongestSubstringTwoDistinct(s) << endl; // 4 45 46 s = "pwwkew"; 47 std::cout << "s: " << s << endl; 48 std::cout << "maxSubstringTwoDistinctLen:"<< test->lengthOfLongestSubstringTwoDistinct(s) << endl; // 3 49 50 delete test; 51 system("pause"); 52 return 0; 53 }

執行結果: