Make The String Great Problem
Description
LeetCode Problem 1544.
Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2s[i]is a lower-case letter ands[i + 1]is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
Return the string after making it good. The answer is guaranteed to be unique under the given constraints.
Notice that an empty string is also good.
Example 1:
Input: s = "leEeetcode"
Output: "leetcode"
Explanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".
Example 2:
Input: s = "abBAcC"
Output: ""
Explanation: We have many possible scenarios, and all lead to the same answer. For example:
"abBAcC" --> "aAcC" --> "cC" --> ""
"abBAcC" --> "abBA" --> "aA" --> ""
Example 3:
Input: s = "s"
Output: "s"
Constraints:
1 <= s.length <= 100scontains only lower and upper case English letters.
Solution
Approach: Stack
Removing a bad pair can create a new bad pair across the gap: in "abBA", removing "bB" leaves "aA", which must go too. This is exactly the behavior of a stack.
Read the characters one by one and keep the good string built so far on a stack:
- If the stack's top is the same letter as
cin the other case, the two cancel: pop the top. - Otherwise push
c.
In ASCII, a lowercase letter is exactly 32 more than its uppercase form ('a' is 97, 'A' is 65), so the test can be |top - c| == 32. Note that two equal characters, like "aa", are not a bad pair.
At the end, the stack holds the answer. The problem says the result is unique, so the order in which we remove pairs does not matter, and the left-to-right order of the stack is as good as any.
Complexity: O(n) time and O(n) space for the stack.
class Solution:
def makeGood(self, s: str) -> str:
stack = [] # the good string built so far
for c in s:
# The same letter in the other case: the pair cancels.
if stack and stack[-1] != c and stack[-1].lower() == c.lower():
stack.pop()
else:
stack.append(c)
return "".join(stack)