Created
March 4, 2022 02:58
-
-
Save ericness/0e15faeb310f0fcd0f86a9e7bc06e29b to your computer and use it in GitHub Desktop.
Leetcode 424 final solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections import defaultdict | |
| class Solution: | |
| def characterReplacement(self, s: str, k: int) -> int: | |
| """Calculate the longer repeating character | |
| string when replacing with one letter | |
| Args: | |
| s (str): String to evaluate | |
| k (int): Number of characters to replace | |
| Returns: | |
| int: Length of longest repeating sequence | |
| """ | |
| behind, ahead = 0, 0 | |
| char_count = defaultdict(int) | |
| char_count[s[ahead]] += 1 | |
| max_length = 0 | |
| while ahead < len(s): | |
| length = ahead - behind + 1 | |
| max_freq = max(char_count.values()) | |
| if length - max_freq <= k: | |
| max_length = max(length, max_length) | |
| ahead += 1 | |
| if ahead == len(s): | |
| break | |
| char_count[s[ahead]] += 1 | |
| else: | |
| char_count[s[behind]] -= 1 | |
| behind += 1 | |
| return max_length |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment