zoukankan      html  css  js  c++  java
  • LeetCode 424. Longest Repeating Character Replacement

    原题链接在这里:https://leetcode.com/problems/longest-repeating-character-replacement/description/

    题目:

    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.

    题解:

    类似快慢指针维护substring的方法在Minimum Window Substring里有总结.

    随着runner向前推进找出最高frequency word的count. substring整个长度减掉最大的count 就是需要调换的字符数, 若大于k就移动walker.

    移动walker时只需要不需要更改maxCount, runner-walker-maxCount自会变小.

    Why we don't need to update maxCount, here we only need to care the longest substring, it is maxCount+k. 

    Thus we only needto care when there is new largert maxCount.

    Here while only execuates once, move walker once, it already break the while condition. 

    Time Complexity: O(s.length()).

    Space: O(1).

    AC Java:

     1 class Solution {
     2     public int characterReplacement(String s, int k) {
     3         int [] map = new int[256];
     4         int walker = 0;
     5         int runner = 0;
     6         int maxCount = 0;
     7         int res = 0;
     8         while(runner < s.length()){
     9             maxCount = Math.max(maxCount, ++map[s.charAt(runner++)]);
    10             while(runner-walker-maxCount > k){
    11                 map[s.charAt(walker++)]--;
    12             }
    13             
    14             res = Math.max(res, runner-walker);
    15         }
    16         return res;
    17     }
    18 }

    类似Longest Substring with At Most Two Distinct Characters.

  • 相关阅读:
    LeetCode 264. Ugly Number II
    LeetCode 231. Power of Two
    LeetCode 263. Ugly Number
    LeetCode 136. Single Number
    LeetCode 69. Sqrt(x)
    LeetCode 66. Plus One
    LeetCode 70. Climbing Stairs
    LeetCode 628. Maximum Product of Three Numbers
    Leetcode 13. Roman to Integer
    大二暑假周进度报告03
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/8412165.html
Copyright © 2011-2022 走看看