You are given a string s, which contains stars *.
In one operation, you can:
s.Return the string after all stars have been removed.
Note:
Example 1:
Input: s = "leet**cod*e" Output: "lecoe" Explanation: Performing the removals from left to right: - The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e". - The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e". - The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe". There are no more stars, so we return "lecoe".
Example 2:
Input: s = "erase*****" Output: "" Explanation: The entire string is removed, so we return an empty string.
Constraints:
1 <= s.length <= 105s consists of lowercase English letters and stars *.s.This approach utilizes a stack data structure to handle the character removals efficiently. As we iterate through the string, whenever a star (*) is encountered, we pop from the stack, effectively removing the last non-star character added. This allows us to handle both the star and its preceding non-star character in O(1) time.
The C implementation uses a character array as a stack to store non-star characters. We increment the top index when adding a character and decrement it when encountering a star, which effectively removes the most recent non-star character.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), for the stack to hold characters.
This alternative method involves using a simple two-pointer technique where we iterate through the string and build the result in place. We treat the string as a writable array and maintain a 'write' index that tells us where to place the next character. When we encounter a star, we just need to move the 'write' index back to overwrite the previous character.
This C implementation makes use of two indices: read, which traverses the string, and write, which indicates where to write the next character.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1), since operations are done in-place.
| Approach | Complexity |
|---|---|
| Stack-based Approach | Time Complexity: O(n), where n is the length of the string. |
| Two-pointer Technique | Time Complexity: O(n) |
Removing Stars From a String - Leetcode 2390 - Python • NeetCodeIO • 33,889 views views
Watch 9 more video solutions →Practice Removing Stars From a String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor