题解 | #包含不超过两种字符的最长子串#
包含不超过两种字符的最长子串
https://www.nowcoder.com/practice/90d6a362fa7d4c519d557da797bb02ce
#include <iostream> #include <string> #include <unordered_map> using namespace std; int lengthOfLongestSubstringTwoDistinct(const string& s) { unordered_map<char, int> charCount; int maxLength = 0; int left = 0; for (int right = 0; right < s.length(); right++) { charCount[s[right]]++; // Increment the count of the character at right // While we have more than two distinct characters, move the left pointer while (charCount.size() > 2) { charCount[s[left]]--; // Decrement the count of the character at left if (charCount[s[left]] == 0) { charCount.erase( s[left]); // Remove the character completely if count goes to zero } left++; // Move the left pointer to the right } // Calculate the current length of the substring maxLength = max(maxLength, right - left + 1); } return maxLength; } int main() { string input; cin >> input; cout << lengthOfLongestSubstringTwoDistinct(input) << endl; return 0; } // 64 位输出请用 printf("%lld")