Problem
You are given a string s
, which contains stars *
.
In one operation, you can:
- Choose a star in
s
. - Remove the closest non-star character to its left, as well as remove the star itself.
Return the string after all stars have been removed.
Note:
- The input will be generated such that the operation is always possible.
- It can be shown that the resulting string will always be unique.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Stack
Given a string s
which contains stars (*
), we need to iteratively remove the closest non-star character to the left of each star, as well as the star itself. Here’s the structured approach:
- Using a Stack:
- A stack is an appropriate data structure for this problem because it allows us to efficiently keep track of characters and remove the closest non-star character when we encounter a star.
- Traverse the string from left to right. Push non-star characters onto the stack.
- When encountering a star (
*
), pop the stack to remove the most recent non-star character, and then continue.
- Result Construction:
- After processing the entire string, the stack will contain the characters of the final resulting string with all necessary removals applied.
- Convert the stack back to a string to obtain the final result.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the strings
. The stack operations (push and pop) areO(1)
, and we traverse the string once. - 🧺 Space complexity:
O(n)
, in the worst case where no stars are present, and all characters are pushed onto the stack.