
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Consecutive Duplicate Characters in Python
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
- if stack is not empty and top of stack is same as s[i], then
- return after joining stack elements
Let us see the following implementation to get better understanding −
Example
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
Advertisements