Removing Stars From a String — LeetCode 2390 Python Solution
MediumStackStringSimulation
- Problem
- #2390
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string s, which contains stars *. In one operation, you can: Choose a star in s.
Example
- Input
- s = "leet**cod*e"
- Output
- "lecoe"
- Explanation
- Performing the removals from left to right:
Python solution
Python
class Solution:
def removeStars(self, s: str) -> str:
ans = []
for c in s:
if c == '*':
ans.pop()
else:
ans.append(c)
return ''.join(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2390. Removing Stars From a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 2390. Removing Stars From a String?
- LeetCode 2390. Removing Stars From a String is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2390. Removing Stars From a String?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 2390. Removing Stars From a String?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2390. Removing Stars From a String cover?
- LeetCode 2390. Removing Stars From a String is tagged Stack, String and Simulation on LeetCode.