Last active
March 14, 2022 09:00
-
-
Save doyedele1/178ac9f71876cd4e58b8132e06c1e251 to your computer and use it in GitHub Desktop.
Remove All Adjacent Duplicates in String II
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
''' | |
Explanation: | |
- deeedbbcccbdaa | |
[[d,1], [e,3]] | |
[[d,2]] | |
TC - O(2n) = O(n) where n is the size of the input string | |
SC - O(n) | |
''' | |
class Solution: | |
def removeDuplicates(self, s: str, k: int) -> str: | |
# create a stack with [character, count] | |
stack = [] | |
for char in s: | |
if stack and stack[-1][0] == char: | |
stack[-1][1] += 1 | |
else: | |
stack.append([char, 1]) | |
if stack and stack[-1][1] == k: | |
stack.pop() | |
# char * num prints the char in num times | |
return "".join([char * num for char, num in stack]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment