Use the output as a stack: pop when the next character matches the top, otherwise push it.
Complexity
O(n) time and O(n) space.
Repeatedly remove equal adjacent character pairs until none remain.
Use the output as a stack: pop when the next character matches the top, otherwise push it.
O(n) time and O(n) space.
package main
func removeDuplicates(s string) string {
stack := []byte{}
for index := range s {
if len(stack) > 0 && stack[len(stack)-1] == s[index] {
stack = stack[:len(stack)-1]
} else {
stack = append(stack, s[index])
}
}
return string(stack)
}
class Solution:
def removeDuplicates(self, s: str) -> str:
stack: list[str] = []
for character in s:
if stack and stack[-1] == character: stack.pop()
else: stack.append(character)
return "".join(stack)
function removeDuplicates(s: string): string {
const stack: string[] = [];
for (const character of s) { if (stack[stack.length - 1] === character) stack.pop(); else stack.push(character); }
return stack.join("");
}