- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find string after removing 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
- Related Articles
- Program to find string after deleting k consecutive duplicate characters in python
- Python program to find all duplicate characters in a string
- Program to find shortest string after removing different adjacent bits in Python
- Java Program to find duplicate characters in a String?
- Program to find cost to remove consecutive duplicate characters with costs in C++?
- Java program to find all duplicate characters in a string
- Java Program to Find the Duplicate Characters in a String
- Program to remove duplicate characters from a given string in Python
- Program to find min length of run-length encoding after removing at most k characters in Python
- Find All Duplicate Characters from a String using Python
- C# Program to remove duplicate characters from String
- Program to find mean of array after removing some elements in Python
- Program to find length of substring with consecutive common characters in Python
- Python Program to Split joined consecutive similar characters
- Python Program to find mirror characters in a string

Advertisements