• 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的情况。

  • 相关阅读:
    Luogu P4316 绿豆蛙的归宿 题解报告
    Luogu P1850 换教室(NOIP 2016) 题解报告
    Rainbow的信号 题解报告
    $CH5105 Cookies$ 线性$DP+$贪心
    算法竞赛 $0×50$ 动态规划 (+一本通
    $CH5104 I-country$ 线性$DP$
    洛谷$2014$ 选课 背包类树形$DP$
    $SP703 Mobile Service DP$
    $POJ1015 Jury Compromise Dp$/背包
    $POJ1742 Coins$ 多重背包+贪心
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6508268.html
Copyright © 2020-2023  润新知