Back to course home
0% completed
Vote For New Content
JS Solution: Iterate over the string from the opposite direction
tai
Oct 22, 2024
Maybe this isn't the "right" approach but since this is a stack problem, iterating over the string in sequential order would end up with a reverse answer, so instead of reversing the stack (which I'm pretty sure goes against the constraints of a stack) I figured you could just iterate over the string from the opposite end. I know JS doesn't include a "peek" method so I decided to just use the stack length to access the ending element (for some reason my browser/code editor won't accept stack.at(-1) but I think this is a bit more reasonable than the given answer in the solution section:
class Solution { removeDuplicates(s) { // ToDo: Write Your Code Here. const stack = [] for (let i = s.length - 1; i > -1; i--) { if (stack.length && stack.at(stack.length - 1) === s[i]) stack.pop(); else stack.push(s[i]); } let result = '' while (stack.length) { result += stack.pop() } return result } }
0
0
Comments
Comments
On this page