You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string.
In one operation, you can choose any character of the string and change it to any other uppercase English character.
Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 10^4.
Example 1:
Input:
s = "ABAB", k = 2
Output:
4
Explanation:
Replace the two 'A's with two 'B's or vice versa.
Example 2:
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.
class Solution {
public int characterReplacement(String s, int k) {
int res = 0, max = 0, left = 0;
final int NUM = 26;
int[] cnt = new int[NUM];
for (int right = 0; right < s.length(); ++right) {
max = Math.max(max, ++cnt[s.charAt(right) - 'A']);
while (right - left + 1 - max > k) {
--cnt[s.charAt(left) - 'A'];
++left;
}
res = Math.max(res, right - left + 1);
}
return res;
}
}
Given a string
s
that consists of only uppercase English letters, you can perform at mostk
operations on that string.In one operation, you can choose any character of the string and change it to any other uppercase English character.
Find the length of the longest sub-string containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 10^4.
Example 1:
Example 2:
不要被k个操作疑惑了,根据连续子字符串,要想到 滑动窗口(sliding windows) 方法。
维护一个窗口,计算窗口内的最大重复字符数量,如果该数量与k的和小于窗口长度,则窗口左边界左移;这样的目的是保持窗口内最大重复字母数量加上操作k限制的操作数量等于窗口长度。
如何找出滑动窗口内出现频率最高的字母也很重要,维护一个26长度的一维数组,表示窗口内对应26个字母的出现次数,每次如果哪个字母出现次数增加,就要做一次判断找出最大频率字母。
参考资料:
The text was updated successfully, but these errors were encountered: