?LeetCode刷題實戰(zhàn)424:替換后的最長重復(fù)字符
You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
示例
示例 1:
輸入:s = "ABAB", k?= 2
輸出:4
解釋:用兩個'A'替換為兩個'B',反之亦然。
示例 2:
輸入:s = "AABABBA", k?= 1
輸出:4
解釋:
將中間的一個'A'替換為'B',字符串變?yōu)?"AABBBBA"。
子串 "BBBB"?有最長重復(fù)字母, 答案為 4。
解題
class?Solution?{
public:
????int?characterReplacement(string?s, int?k)?{
????????vector<int> counts(26, 0); //記錄當(dāng)前窗口字母出現(xiàn)的個數(shù)
????????int?left=0, res=0, maxCnt=0; // maxCnt記錄字符出現(xiàn)次數(shù)最多那個字符 的次數(shù)
????????for(int?i=0; i????????????counts[s[i]-'A']++;
????????????maxCnt = max(maxCnt, counts[s[i]-'A']); // 比較之前記錄的最大數(shù) 和 當(dāng)前字符的數(shù)量
????????????while(i-left+1-maxCnt > k){ // 若當(dāng)前窗口大小 減去 窗口中最多相同字符的個數(shù) 大于 k 時
????????????????counts[s[left]-'A']--; // 將窗口最左邊的字符 在計數(shù)數(shù)組中減1
????????????????left++; // 滑動窗口
????????????}
????????????res = max(res, i-left+1);
????????}
????????return?res;
????}
};
LeetCode刷題實戰(zhàn)421:數(shù)組中兩個數(shù)的最大異或值
LeetCode刷題實戰(zhàn)423:從英文中重建數(shù)字
