Back to Leetcode Go

1047. Remove All Adjacent Duplicates In String

website/content.en/ChapterFour/1000~1099/1047.Remove-All-Adjacent-Duplicates-In-String.md

1.7.971.8 KB
Original Source

1047. Remove All Adjacent Duplicates In String

Problem

Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on S until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.

Example 1:


Input: "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Note:

  1. 1 <= S.length <= 20000
  2. S consists only of English lowercase letters.

Problem Summary

Given a string S consisting of lowercase letters, a duplicate removal operation chooses two adjacent and identical letters and deletes them. Repeatedly perform duplicate removal operations on S until no further deletions can be made. Return the final string after all duplicate removal operations have been completed. The answer is guaranteed to be unique.

Solution Approach

Use a stack to simulate the process, similar to a “matching game.” Once the incoming character is the same as the character on the top of the stack, pop the top character from the stack, until the entire string has been scanned. The string left in the stack is the final result to output.

Code

go

package leetcode

func removeDuplicates1047(S string) string {
	stack := []rune{}
	for _, s := range S {
		if len(stack) == 0 || len(stack) > 0 && stack[len(stack)-1] != s {
			stack = append(stack, s)
		} else {
			stack = stack[:len(stack)-1]
		}
	}
	return string(stack)
}