[leetcode - Bliend-75 ] 424. Longest Repeating Character Rep

You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.

Return the length of the longest substring containing the same letter you can get after performing the above operations.

给一个字串 s 可以随意变换 s 中的字元 k 次,找到相同字源的最长长度。

Example

Input: s = "ABAB", k = 2
Output: 4
Explanation: Replace the two 'A's with two 'B's or vice versa.

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.
There may exists other ways to achieve this answer too.

Coding

var characterReplacement = function(s, k) {  let l = 0, max = 0, mostCounts = 0, map = {};  for (let r = 0; r < s.length; r++) {    if (!map[s[r]]) map[s[r]] = 1;    else map[s[r]]++;    mostCounts = Math.max(mostCounts, map[s[r]]);    if ((r - l + 1) - mostCounts > k) {      map[s[l]]--;      l++;    }    max = Math.max(max, r - l + 1);  }  return max;};

http://img2.58codes.com/2024/inr5gGV.gif

R = 0, L = 0map = { 'A': 1 },mostCounts = 1sub-string = 'A'sub-string length = 1(sub-string length) - 1 < 1R = 1, L = 0map = { 'A': 2 },mostCounts = 2sub-string = 'AA'sub-string length = 2(sub-string length) - 2 < 1R = 2, L = 0map = { 'A': 2, 'B': 1 },mostCounts = 2sub-string = 'AAB'sub-string length = 3(sub-string length) - 2 = 1R = 3, L = 0map = { 'A': 3, 'B': 1 },mostCounts = 3sub-string = 'AABA'sub-string length = 4(sub-string length) - 3 = 1R = 4, L = 0map = { 'A': 3, 'B': 2 },mostCounts = 3sub-string = 'AABAB'sub-string length = 5(sub-string length) - 3 > 1 (X) 移除 sub-string 的第一个字元, L 往右移动一格R = 5, L = 1map = { 'A': 2, 'B': 3 },mostCounts = 3sub-string = 'ABABB'sub-string length = 5(sub-string length) - 3 > 1 (X) 移除 sub-string 的第一个字元, L 往右移动一格R = 6, L = 2map = { 'A': 2, 'B': 3 },mostCounts = 3sub-string = 'BABBA'sub-string length = 5(sub-string length) - 3 > 1 (X) 移除 sub-string 的第一个字元, L 往右移动一格

Time complexity: O(n)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章