Given a string s
that consists of only uppercase English letters, you can perform at most k
operations on that string.
In one operation, you can choose any character of the string and change it to any other uppercase English character.
Find the length of the longest sub-string 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.
class Solution:
def characterReplacement(self, s: str, k: int) -> int:
# Time complexity: O(n).
# Space complexity: O(26) ~ O(1).
n = len(s)
char_freqs = [0] * 26
beg = 0
max_length = 0
max_freq = 0 # maximum char frequency within window size.
for end in range(n):
char_freqs[ord(s[end]) - ord('A')] += 1
freq = char_freqs[ord(s[end]) - ord('A')]
max_freq = max(max_freq, freq)
while end - beg + 1 - max_freq > k:
char_freqs[ord(s[beg]) - ord('A')] -= 1
beg += 1
max_length = max(max_length, end - beg + 1)
return max_length
https://leetcode.com/problems/find-k-closest-elements/ Naive def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: L = sorted([(abs(elt - x), elt) for elt in arr], key=lambda tup: tup[0]) return sorted([tup[1] for tup in L[:k]]) Opti
Sep 23, 2022Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack();
Jun 27, 2022Given a string containing just the characters $($, $)$, ${$, $}$, $[$ and $]$, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Jun 27, 2022Solution 1 Time complexity: O(n³) Space complexity: O(n) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return []
Apr 23, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up