Program to find string after removing consecutive duplicate characters in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s, we repeatedly delete the first consecutive duplicate characters. We have to find the final string.

So, if the input is like s = "xyyyxxz", then the output will be "z", as "yyy" are the first consecutive duplicate characters which will be deleted. So we have "xxxz". Then "xxx" will be deleted to end up with "z".

To solve this, we will follow these steps −

  • stack := a new stack
  • i := 0
  • while i < size of s, do
    • if stack is not empty and top of stack is same as s[i], then
      • x := delete last element from stack
      • while i < size of s and x is same as s[i], do
        • i := i + 1
      • i := i - 1
    • otherwise,
      • push s[i] into stack
    • i := i + 1
  • return after joining stack elements

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s):
      stack = []
      i = 0
      while i < len(s):
         if len(stack) and stack[-1] == s[i]:
            x = stack.pop()
            while i < len(s) and x == s[i]:
               i += 1
            i -= 1
            else:
               stack.append(s[i])
            i += 1
      return "".join(stack)
ob = Solution()
s = "xyyyxxz"
print(ob.solve(s))

Input

"xyyyxxz"

Output

z
raja
Published on 20-Oct-2020 14:16:32
Advertisements