【424. 替换后的最长重复字符】
Leetcode算法练习 笔记记录
- 424. 替换后的最长重复字符
424. 替换后的最长重复字符
这里还是借用Leetcode1004的思想,把问题变成将其他字符替换为目标字符后哪一种最长
public int characterReplacement(String s, int k) {//如果只有1个直接返回1if (s.length() == 1) {return 1;}//如果是同一种字符串,直接返回长度,因为直接是最长的char[] array = s.toCharArray();Set<Character> set = new HashSet<>();for (char c : array) {set.add(c);}if (set.size() == 1) {return s.length();}int max = Integer.MIN_VALUE;for (char c : set) {int curMax = handle(k, array, c);max = Math.max(max, curMax);}return max;}private static int handle(int k, char[] array, char target) {int max = 0;int left = 0;int replaceCount = 0;for (int right = 0; right < array.length; right++) {if (array[right] != target) {replaceCount++;}while (replaceCount > k) {if (array[left] != target) {replaceCount--;}left++;}max = Math.max(max, right - left + 1);}return max;}