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.
给一个字串 s 可以随意变换 s 中的字元 k 次,找到相同字源的最长长度。
Example
Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.
Input: s = "AABABBA", k = 1
Output: 4
Explanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".
The substring "BBBB" has the longest repeating letters, which is 4.
There may exists other ways to achieve this answer too.
Coding
var characterReplacement = function(s, k) { let l = 0, max = 0, mostCounts = 0, map = {}; for (let r = 0; r < s.length; r++) { if (!map[s[r]]) map[s[r]] = 1; else map[s[r]]++; mostCounts = Math.max(mostCounts, map[s[r]]); if ((r - l + 1) - mostCounts > k) { map[s[l]]--; l++; } max = Math.max(max, r - l + 1); } return max;};