424. Longest Repeating Character Replacement
View on LeetCode ↗
C++
class Solution {public: int characterReplacement(string s, int k) { int best = 0; int l = 0; unordered_map<char, int> mapping; char maxc = ' '; int maxcount = 0; for (int r = 0; r < s.size(); r++) { // going to add char to window first mapping[s[r]] += 1; // look through mapping for most common char so far if (mapping[s[r]] >= maxcount) { maxc = s[r]; maxcount = mapping[s[r]]; } // cout << l << " " << r << " " << maxc << " " << maxcount << // endl; // now fix the sliding window by decreasing l until its valid while ((r - l + 1) - maxcount > k) { // cout << (r - l + 1) - maxcount << endl; // cout << l << " " << r << endl; mapping[s[l]]--; // if (s[l] == maxc){ // maxcount--; // } l++; } // then update best; best = max(best, r - l + 1); } return best; }};