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

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

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

    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. es6 数组实例的 find() 和 findIndex()

    数组实例的find方法,用于找出第一个符合条件的数组成员.它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员.如果没有符合条件的成员,则返回u ...

  2. 关于nginx重新编译

    nginx安装成功后,发现有一些其他模块没有编译进去,或者想额外添加一些模块,这时候就要重新编译nginx. 首先,查看之前编译的一些参数,比如: 1 2 3 4 5 [root@lmode ngin ...

  3. 2015年蓝桥杯省赛A组c++第8题(迭代法)

    /* 乐羊羊饮料厂正在举办一次促销优惠活动.乐羊羊C型饮料,凭3个瓶盖可以再换一瓶C型饮料, 并且可以一直循环下去(但不允许暂借或赊账). 请你计算一下,如果小明不浪费瓶盖,尽量地参加活动,那么,对于 ...

  4. android实现手势锁

    通过简单的设置后即可实现简单的手势锁: setLineVisible方法设置是否显示手势路径: setLineWidth方法设置手势路径连线的粗细: setLineColor方法设置常规状态手势路径连 ...

  5. mybatis获取批量插入的主键自增id

    一.写一个实体类 public class UserInfo { private long userId; private String userAccount; private String use ...

  6. Django 之Redis配置

    目的:访问服务器频繁的读取数据库 ,会耗损服务器性能及降低用户体验,为此引入Redis 1,安装 redis(2.10.6兼容性更好) pip install redis 2,settings.py配 ...

  7. Maven项目常见的小问题

    pom.xml文件头报错 场景 例Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4 from ...

  8. numpy——.npy和.npz文件

    npy文件--Numpy专用的二进制格式np.load()和np.save()是读写磁盘数组数据的两个重要函数.使用时,数组会以未压缩的原始二进制格式保存在扩展名为.npy的文件中. import n ...

  9. 洛谷P3041 视频游戏的连击Video Game Combos [USACO12JAN] AC自动机+dp

    正解:AC自动机+dp 解题报告: 传送门! 算是个比较套路的AC自动机+dp趴,,, 显然就普普通通地设状态,普普通通地转移,大概就f[i][j]:长度为i匹配到j 唯一注意的是,要加上所有子串的贡 ...

  10. 帝国cms如何调用指定id的文章到首页?

    小美女用帝国cms建了一个站,现在首页调出指定id为12的文章作为推荐,附带文章摘要,她想用代码的形式直接掉用,以后方便修改.那么,帝国cms如何调用指定id的文章呢?指定信息id,不是调用指定栏目i ...