-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy path424_Longest_Repeating_Character_Replacement.py
33 lines (29 loc) · 1.31 KB
/
424_Longest_Repeating_Character_Replacement.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution(object):
def characterReplacement(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
startIdx, endIdx, maxSubStrLen, maxCountOfMostCommonCharInWindow = 0, 0, 0 ,0
charFrequencyCountIntoWindow = [0 for _ in range(26)]
while endIdx < len(s):
currentCharIdx = ord(s[endIdx]) - ord('A')
charFrequencyCountIntoWindow[currentCharIdx] += 1
maxCountOfMostCommonCharInWindow = max(maxCountOfMostCommonCharInWindow, charFrequencyCountIntoWindow[currentCharIdx])
slidingWindowLenght = endIdx - startIdx + 1
numOfReplacement = slidingWindowLenght - maxCountOfMostCommonCharInWindow
while numOfReplacement > k:
idxOfStartingWindowCharIntoCharFrequenctArray = ord(s[startIdx]) - ord('A')
charFrequencyCountIntoWindow[idxOfStartingWindowCharIntoCharFrequenctArray] -= 1
startIdx += 1
slidingWindowLenght = endIdx - startIdx + 1
numOfReplacement = slidingWindowLenght - maxCountOfMostCommonCharInWindow
maxSubStrLen = max(maxSubStrLen, slidingWindowLenght)
endIdx += 1
return maxSubStrLen
sol = Solution()
s = "AABABBA"
k = 1
out = sol.characterReplacement(s, k)
print("Res: ", out)