1544. Make The String Great

Overview
If there is a pair of the same letter with one lowercase and one uppercase, remove the pair of letters.
Until there are no pair of letters, that is a great string.
Solution 1: Stack
Algorithm
-
Initialize a
stackto save characters. -
Iterate through the string
s:- If the
stackis not empty and the ASCII code of thecharacterminus the ASCII code of the last element of the stack equals to 32 in absolute value.
That indicates that thecharacterand the last element of the stack form a pair of the same letter, with one being uppercase and the other being lowercase.
Pop out the last element from the stack.
We keep only unpaired letters inside thestack. - Otherwise, append the
characterto thestack.
- If the
-
Join the
stackinto a string and return.
Implement
class Solution: def makeGood(self, s: str) -> str: stack: list[str] = [] for char in s: if stack and abs(ord(char) - ord(stack[-1])) == 32: stack.pop() else: stack.append(char) return ''.join(stack)
Complexity Analysis
Time complexity: O(n)
Iterating through the string s takes O(n) time, where n is the length of the string.
Space complexity: O(n)
Using an additional stack to store the characters takes O(n) space, where n is the length of the string.