[LeetCode] 424. Longest Repeating Character Replacement

Longest repeating characters after replacement. Meaning of the questions is to give a string, only uppercase letters, allowing you to replace one of the letters K, asked the same replacement operation after the completion of the longest letter to return the length of the substring is. example,

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.

Ideas or sliding window (sliding window). Specifically, the following

  • Create a map for each letter and record their number of occurrences
  • Start and end with two pointers stuck window
  • end the first move, and at the same time with a variable max find the largest number of elements of the present situation and the number of
  • If the current window size - K> max, considering the reduced window size - start pointer move
  • After the window size is reduced to less than max, the current value of a recording window, the value of the length is the longest repeated substring

Time O (n)

A length of the array 26 - space O (1)

Java implementation

 1 class Solution {
 2     public int characterReplacement(String s, int k) {
 3         int[] count = new int[26];
 4         int start = 0;
 5         int res = 0;
 6         int max = 0;
 7         for (int end = 0; end < s.length(); i++) {
 8             count[s.charAt(end) - 'A']++;
 9             max = Math.max(max, count[s.charAt(end) - 'A']);
10             // need to shrimp start - end
11             if (end - start + 1 - max > k) {
12                 count[s.charAt(start) - 'A']--;
13                 start++;
14             }
15             res = Math.max(res, end - start + 1);
16         }
17         return res;
18     }
19 }

 

JavaScript implementation

 1 /**
 2  * @param {string} s
 3  * @param {number} k
 4  * @return {number}
 5  */
 6 var characterReplacement = function(s, k) {
 7     let count = {};
 8     let start = 0;
 9     let max = 0;
10     let res = 0;
11     for (let end = 0; end < s.length; end++) {
12         count[s[end]] = count[s[end]] + 1 || 1;
13         max = Math.max(max, count[s[end]]);
14         if (end - start + 1 - max > k) {
15             count[s[start]]--;
16             start++;
17         }
18         res = Math.max(res, end - start + 1);
19     }
20     return res;
21 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12630114.html