Sponsored
Sponsored
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.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), for the stack to hold characters.
1def removeStars(s: str) -> str:
2 result = []
3 for c in s:
4 if c == '*':
5 if result:
6 result.pop()
7 else:
8 result.append(c)
9 return ''.join(result)
10
11s = "leet**cod*e"
12print(removeStars(s))
In this Python solution, a list is used as a stack to keep track of non-star characters. We pop
the last element on encountering a star.
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.
Time Complexity: O(n)
Space Complexity: O(1), since operations are done in-place.
1
This C implementation makes use of two indices: read
, which traverses the string, and write
, which indicates where to write the next character.