[LeetCode]#1047. Remove All Adjacent Duplicates In String

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".
  1. If S[i] is equal ans[-1], remove this element “b” and “a”.
  2. Return ‘ca’
class Solution:
def removeDuplicates(self, S):
ans=[]

for i in range(len(S)):
if len(ans) > 0:
if S[i] == ans[-1]:
ans.pop()
else:
ans.append(S[i])
else:
ans.append(S[i])
return ''.join(ans)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Fatboy Slim

Fatboy Slim

Interesting in any computer science.