Remove All Adjacent Duplicates In String in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string S of lowercase letters; a duplicate removal operation will be performed. This will be done by choosing two adjacent and equal letters, and removing them.

We will repeatedly remove duplicates from S until no duplicates are remaining.

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

Suppose the string is “abbacaca”, then answer will be “caca”. At first delete duplicates bb, then string is “aacaca”, then remove aa, then string is “caca”, then no such duplicates are there.

To solve this, we will follow these steps −

  • Define an array st, and initialize i := 0
  • while i < length of string −
    • if st has some element, and last element of st = st[i], then increase i by 1, and delete last element from st
    • otherwise add string[i] into st, increase i by 1
  • finally join all elements in st as a string and return

Example

Let us see the following implementation to get better understanding −

 Live Demo

class Solution(object):
   def removeDuplicates(self, S):
      st = []
      i = 0
      while i < len(S):
         if len(st)!=0 and st[-1]==S[i]:
            i+=1
            st.pop(-1)
         else:
            st.append(S[i])
            i+=1
      return "".join(i for i in st)
ob1 = Solution()
print(ob1.removeDuplicates("abbacaca"))

Input

"abbacaca"

Output

"caca"
raja
Published on 16-Jan-2020 16:43:57
Advertisements