424. Longest Repeating Character Replacement
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Note:
Both the string's length and k will not exceed 104.
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.
此题题目如果能读懂的话,就算成功了,看了答案,大致意思是,遍历整个字符串,当到某一个字符的时候,end-start+1-包含字符个数最多的个数>k时候,把最左面的字符在数组里面出现的次数减一
并且start向右遍历,代码如下:
1 public class Solution { 2 public int characterReplacement(String s, int k) { 3 int start = 0; 4 int end = 0; 5 int[] count = new int[26]; 6 int max = 0; 7 int mainmax = 0; 8 for(;end<s.length();end++){ 9 mainmax = Math.max(mainmax,++count[s.charAt(end)-'A']); 10 while(end-start-mainmax+1>k){ 11 count[s.charAt(start)-'A']--; 12 start++; 13 } 14 max = Math.max(max,end-start+1); 15 } 16 return max; 17 } 18 }
此题说白了就是,进行两次比较,一次记录出现字符数目最多的情形,另外一次记录出现的最大长度,while来处理数目大于k的情况。