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.

真是被这道题气死了,总是弄不对

The problem says that we can make at most k changes to the string (any character can be replaced with any other character). So, let's say there were no constraints like the k. Given a string convert it to a string with all same characters with minimal changes. The answer to this is

length of the entire string - number of times of the maximum occurring character in the string

Given this, we can apply the at most k changes constraint and maintain a sliding window such that

(length of substring - number of times of the maximum occurring character in the substring) <= k

The initial step is to extend the window to its limit, that is, the longest we can get to with maximum number of modifications. Until then the variable start will remain at 0.

Then as end increase, the whole substring from 0 to end will violate the rule, so we need to update start accordingly (slide the window). We move start to the right until the whole string satisfy the constraint again. Then each time we reach such situation, we update our max length.

Prefered solution:

 class Solution {
public int characterReplacement(String s, int k) {
int[] counts = new int[26];
int l = 0, r = 0, res = 0;
char maxChar = '\0';
int maxCount = 0;
for (; r < s.length(); r ++) {
char cur = s.charAt(r);
counts[cur - 'A'] ++;
if (counts[cur - 'A'] > maxCount) {
maxCount = counts[cur - 'A'];
maxChar = cur;
}
while (l<= r && r - l + 1 > maxCount + k) {
counts[s.charAt(l) - 'A'] --;
if (s.charAt(l) == maxChar) {
maxCount = counts[s.charAt(l) - 'A'];
for (int t = 0; t < 26; t ++) {
if (counts[t] > maxCount) {
maxCount = counts[t];
maxChar = (char)('A' + t);
}
}
}
l ++;
}
res = Math.max(res, r - l + 1);
}
return res;
}
}

Another Solution Window never shrink:

 public int characterReplacement(String s, int k) {
int[] charCount = new int[26]; int left, right, maxCount, maxLen;
left = right = maxCount = maxLen = 0; while(right < s.length()){
charCount[s.charAt(right) - 'A']++;
maxCount = Math.max(maxCount, charCount[s.charAt(right) - 'A']);
if(right - left + 1 - maxCount > k) charCount[s.charAt(left++) - 'A']--;
maxLen = Math.max(right++ - left + 1, maxLen);
}
return maxLen;
}

  

Very easy and simple Python solution: (Idea the same but easy to understand)

 import collections
def findLongestSubstring(s,k):
res=0
left=0
counts = collections.Counter()
for right in range(0,len(s)):
counts[s[right]] += 1
char_w_maxCount = counts.most_common(1)[0][1]
while right - left - char_w_maxCount + 1 > k:
counts[s[left]] -= 1
char_w_maxCount = counts.most_common(1)[0][1]
left +=1 res = max(res,right-left+1) return res print(findLongestSubstring("abab",2)) 4
print(findLongestSubstring("aabbbba",1)) 5
print(findLongestSubstring("abcaea",1)) 3
print(findLongestSubstring("aababba",1)) 4
print(findLongestSubstring("abcae",2)) 4
print(findLongestSubstring("aaaaa",2)) 5

Leetcode: Longest Repeating Character Replacement && G 面经的更多相关文章

  1. G 面经 && Leetcode: Longest Repeating Character Replacement

    Given a string that consists of only uppercase English letters, you can replace any letter in the st ...

  2. [LeetCode] Longest Repeating Character Replacement 最长重复字符置换

    Given a string that consists of only uppercase English letters, you can replace any letter in the st ...

  3. LeetCode——Longest Repeating Character Replacement

    1. Question Given a string that consists of only uppercase English letters, you can replace any lett ...

  4. LeetCode 424. Longest Repeating Character Replacement

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

  5. 【LeetCode】424. 替换后的最长重复字符 Longest Repeating Character Replacement(Python)

    作者: 负雪明烛 id: fuxuemingzhu 公众号:每日算法题 本文关键词:LeetCode,力扣,算法,算法题,字符串,双指针,刷题群 目录 题目描述 题目大意 解题方法 双指针 代码 欢迎 ...

  6. 【leetcode】424. Longest Repeating Character Replacement

    题目如下: Given a string that consists of only uppercase English letters, you can replace any letter in ...

  7. [Swift]LeetCode424. 替换后的最长重复字符 | Longest Repeating Character Replacement

    Given a string that consists of only uppercase English letters, you can replace any letter in the st ...

  8. leetcode424 Longest Repeating Character Replacement

    """ Given a string s that consists of only uppercase English letters, you can perform ...

  9. 424 Longest Repeating Character Replacement 替换后的最长重复字符

    给你一个仅由大写英文字母组成的字符串,你可以将任意位置上的字符替换成另外的字符,总共可最多替换 k 次.在执行上述操作后,找到包含重复字母的最长子串的长度.注意:字符串长度 和 k 不会超过 104. ...

随机推荐

  1. BZOJ4500: 矩阵

    Description 有一个n*m的矩阵,初始每个格子的权值都为0,可以对矩阵执行两种操作: 1. 选择一行, 该行每个格子的权值加1或减1. 2. 选择一列, 该列每个格子的权值加1或减1. 现在 ...

  2. js之获取窗口大小和位置信息

    除IE外的浏览器查看窗口大小和位置信息: //The overall size of the browser window on the desktop var windowWidth = windo ...

  3. 纪念逝去的岁月——C/C++字符串旋转

    几年前,我还不会写这个 例如: 1.向右→旋转5个字符 输入:HelloWorld 输出:WorldHello 2.向右→旋转3个字符 输入:HelloWorld 输出:rldHelloWo 代码 # ...

  4. JSONP的小示例

    jQuery中JSONP的两种实现方式: 都很简单,所以直接上代码! 前台代码如下: <script type="text/javascript"> $(functio ...

  5. onselectstart

    以前在做图片滚动时,在双击左右箭头,快速切换图片滚动时,会选择附近区域的文字,感觉不是很好,今天在同事在分享时,讲到了这个问题, 试了一下,不错,解决了问题IE及Chrome下的方法一样,对相应的元素 ...

  6. 1071. Speech Patterns (25)

    People often have a preference among synonyms of the same word. For example, some may prefer "t ...

  7. Centos 安装了 Wkhtmltopdf 却依旧显示 无法打印pdf

    Odoo里判断wkhtmlpdf是否安装的代码在 openerp/tools/misc.py 文件中: def find_in_path(name): path = os.environ.get('P ...

  8. android几个实用的判定代码

    之前项目有几个判定代码很实用,特此做一个整理. 一.验证手机格式是否正确 //判断手机号码是否合理 private boolean judgePhoneNums(String phoneNums) { ...

  9. jquery过滤器

    <html> <head> <meta charset="UTF-8"> <title>Document</title> ...

  10. js 数组排序

    sort()方法使数组中的元素按照一定的顺序排列. 语法: arrayObject.sort(方法函数) 参数说明: 1.如果不指定<方法函数>,则按unicode码顺序排列. 2.如果指 ...