Collapse Equal Adjacent Pairs
Problem statement
You are given a string s of uppercase English letters.
While the string has two equal letters next to each other, remove both of them. The letters on each side then become neighbors, which can create a new equal pair. Keep going until no two neighboring letters are equal, and return the final string.
The final string is the same no matter which pair you remove first. It can be the empty string.
Function
collapseEqualPairs(s: String) → StringExamples
Example 1
s = "ABBCDDC"return = "A"Remove DD to get ABBCC. Then remove CC to get ABB, and remove BB to get A. A single letter has no neighbor, so the answer is "A".
Example 2
s = "AABBAA"return = ""Remove BB to get AAAA. Remove one AA pair to get AA, then remove that pair too. Nothing is left, so the answer is the empty string.
Example 3
s = "BAAAB"return = "BAB"Removing one pair from AAA leaves a single A, which gives BAB. The two B letters are not next to each other, so nothing else can be removed and the answer is "BAB".
Example 4
s = "ABCD"return = "ABCD"No two neighboring letters are equal, so nothing is removed.
Constraints
1 <= s.length <= 10^5scontains only uppercase English letters'A'to'Z'.