标签:script out star param nat color one substr java实现
替换后的最长重复字符。题意是给一个字符串,只有大写字母,允许你替换其中的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)。具体做法如下
时间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
标签:script out star param nat color one substr java实现
原文地址:https://www.cnblogs.com/aaronliu1991/p/12630114.html