题目如下:
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.
解题思路:对于任意一个区间[i,j]能否经过至多K次替换可以变成只包含同一个字符的子串,只要判断除去其中某一个字符,其余剩下的字符的总和不超过K即可。所以本题的解题就是就是找到符合这个条件的最长区间。怎么找这个区间?我的方法是引入low和high两个index,从字符串头部开始遍历,依次判断[low,high]区间是否满足条件,满足的话high += 1,不满足则low += 1。
代码如下:
class Solution(object): def check(self,dic,total,k): mv = 0 flag = False for i in dic.iterkeys(): if total - dic[i] <= k: flag = True mv = max(mv,total) if flag == False and len(dic) > 0: return -1 return mv def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ if len(s) == 0: return 0 low = 0 high = 1 dic = {} dic[s[0]] = 1 total = 1 res = 0 s += '#' while low < high and high < len(s): rc = self.check(dic,total,k) if rc == -1: dic[s[low]] -= 1 total -= 1 if dic[s[low]] == 0: del dic[s[low]] low += 1 else: dic[s[high]] = dic.setdefault(s[high],0) + 1 total += 1 high += 1 res = max(res,rc) return res