Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to replace the longest repeated string in LeetCode

Shulou Source: shulou.com Published: 2022-06-02 05:50:58 09月12日 Update

LeetCode how to replace the longest repeated string, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Topic description:

To give you a string of only uppercase letters, you can replace characters anywhere with other characters, up to a total of k times. After doing the above, find the length of the longest substring containing duplicate letters.

Note: the string length and k will not exceed 10 ^ 4.

Example 1:

Enter: s = "ABAB", k = 2

Output: 4

Explanation: replace two "A" with two "Bones" and vice versa.

Example 2:

Enter: s = "AABABBA", k = 1

Output: 4

Explanation:

Replace the middle'A 'with' AABBBBA 'and change the string to "string".

The substring "BBBB" has the longest repeating letter, and the answer is 4

Analysis of ideas:

When you see the longest string, you think of a sliding window.

Algorithm flow: after the right boundary is moved first to find a replacement for k characters that satisfy the meaning of the question, all characters become the same, which currently appears to be the longest substring, until the right boundary is included in a character and stops when it is not satisfied. then consider that the left boundary moves to the right, and after the left boundary only needs to move one grid to the right, the right boundary can begin to move to the right again and continue to try to find a longer target substring. The longest repeated substring after replacement occurs when the right boundary and the left boundary move alternately to the right. Class Solution:

Def characterReplacement (self, s: str, k: int)-> int:

From collections import defaultdict

D = defaultdict (int)

L = 0

Maxn = 0

For r in range (len (s)):

D [s] + = 1

Maxn = max (maxn, d [s]])

If r-l + 1 > maxn + k: # bc it is for loop, r + = 1 is later than if clause

D [s]-= 1

L + = 1

Return len (s)-l

Class Solution {

Public int characterReplacement (String s, int k) {

Int len=s.length ()

If (len

Tags: Character longest string move right letter two content method more example length problem interpretation input output helpless for this location reason Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB vpn Microsoft Shulou Technology NVidia