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.
1function removeStars(s) {
2 const result = [];
3 for (const char of s) {
4 if (char === '*') {
5 if (result.length) result.pop();
6 } else {
7 result.push(char);
8 }
9 }
10 return result.join('');
11}
12
13console.log(removeStars("leet**cod*e"));
In JavaScript, an array is used to simulate stack operations. The pop
method handles the removal of the last character upon 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.
This C implementation makes use of two indices: read
, which traverses the string, and write
, which indicates where to write the next character.