至多包含两个不同字符的最长子串
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 }
运行结果:

浙公网安备 33010602011771号