- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
Remove All Adjacent Duplicates In String in Python
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
Let us see the following implementation to get better understanding −
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"))
- Related Articles
- Remove All Adjacent Duplicates in String II in C++
- Remove all duplicates from a given string in Python
- Remove all duplicates from a given string in C#
- Remove Consecutive Duplicates in Python
- Remove Duplicates from Sorted Array in Python
- Print a closest string that does not contain adjacent duplicates in C++
- Python program to remove all duplicates word from a given sentence.
- How to remove all leading whitespace in string in Python?
- Print all the duplicates in the input string in C++
- How to remove all trailing whitespace of string in Python?
- Python - Ways to remove duplicates from list
- How do you remove duplicates from a list in Python?
- C# program to remove all duplicates words from a given sentence
- Java program to remove all duplicates words from a given sentence