Make The String Great

To solve this problem, we can use a stack data structure.

Start by initializing an empty stack. We’ll iterate through the string from left to right. For each character, we’ll check the top of the stack. If the stack isn’t empty and the current character and the character at the top of the stack are of opposite cases and same letters, we’ll remove the character at the top of the stack. Otherwise, we’ll push the current character onto the stack.

At the end, the string formed by the characters in the stack is the answer.

Here is the code:

1
2
3
4
5
6
7
8
9
class Solution:
    def makeGood(self, s: str) -> str:
        stack = []
        for c in s:
            if stack and stack[-1].swapcase() == c:
                stack.pop()
            else:
                stack.append(c)
        return ''.join(stack)

In this code, stack[-1].swapcase() checks if the character at the top of the stack is of opposite case and same letter as the current character c. stack.pop() removes the character at the top of the stack, and stack.append(c) adds the current character to the top of the stack. The join method combines all the characters in the stack into a single string.