力扣424
https://leetcode-cn.com/problems/longest-repeating-character-replacement/
滑动窗口题目,需要用数组或者map统计每个字母出现的次数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public int characterReplacement2(String s, int k) { int l = 0, r = 0, res = 0, count = 0; int[] alph = new int[26];
char[] ch = s.toCharArray(); while(r < ch.length){ alph[ch[r] - 'A']++; count = Math.max(count, alph[ch[r] - 'A']); r++;
if(r - l > count + k){ alph[ch[l] - 'A']--; l++; } res = Math.max(res, r - l); }
return res; }
|
python实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def characterReplacement(self, s: str, k: int) -> int: l, r, res, count = 0, 0, 0, 0 alph = {}
while r < len(s): if s[r] in alph: alph[s[r]] += 1 else: alph[s[r]] = 1 count = max(count, alph[s[r]]) r += 1
if r - l > count + k: alph[s[l]] -= 1 l += 1 res = max(count, r - l)
return res
|
其他滑动窗口类型的题目可以点击这里
其他字符串类型的题目可以点击这里