LeetCode: Removing Stars From a String

Remove stars from a string using a stack approach.

Posted on LeetCode Python

Solution

Create a stack of characters to contain the answer.

Loop through each character in the string. If the character is a star (*), pop the last character from the stack. Otherwise, append the character to the stack.

Finally, join the characters in the stack to form the resulting string without stars.

Runtime

90 ms | Beats 83.71%

class Solution:
def removeStars(self, s: str) -> str:
answer = []
for c in s:
if c == "*":
answer.pop()
else:
answer.append(c)
return "".join(answer)

Note: I attempted this problem with a two-pointer solution, just to compare performance. That solution times out on large test cases. In this example, you move through the string, tracking the last non-star character with one pointer and the current character with another pointer.