[LeetCode] 424. Longest Repeating Character Replacement

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 424. Longest Repeating Character Replacement相关的知识,希望对你有一定的参考价值。

替换后的最长重复字符。题意是给一个字符串,只有大写字母,允许你替换其中的K个字母,问替换操作完成后能返回的最长字母相同的子串的长度是多少。例子,

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.

思路还是滑动窗口(sliding window)。具体做法如下

  • 创建一个map记录每个字母和他们的出现次数
  • 用两个指针start和end卡住窗口
  • end先移动,并同时用一个变量max找到目前出现次数最多的元素及其次数
  • 如果当前窗口size - K > max,则考虑缩小窗口尺寸 - 挪动start指针
  • 窗口size缩减到小于max之后,记录一个当前窗口的值,这个值就是最长重复子串的长度

时间O(n)

空间O(1) - 一个26位长度的数组

Java实现

 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实现

 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 };

 

以上是关于[LeetCode] 424. Longest Repeating Character Replacement的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 424. Longest Repeating Character Replacement

424. Longest Repeating Character Replacement

424. Longest Repeating Character Replacement

424. Longest Repeating Character Replacement - Medium

[LeetCode] Longest Word In Dictionary

[leetcode]Trie-720. Longest Word in Dictionary