Removing Stars From a String - Stack [JS]
Solution: Stack
Reverse s
, instead of removing the closest to the left, remove the closest to the right.
We can then use a stack to efficiently find and remove the closest non-star on the right.
The top of the stack is the closest non-star on the right.
Whatever is left in the stack are the final characters.
Time Complexity: O(n)
Space Complexity: O(n)
var removeStars = function(s) {
s = s.split("").reverse();
let stack = [], n = s.length;
for (let i = n - 1; i >= 0; i--) {
if (s[i] === '*') stack.pop();
else stack.push(s[i]);
}
return stack.join("");
};
Comments
Post a Comment