

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 Duplicates in Python
Suppose we have a string s, this string consisting of "R" and "L", we have to remove the minimum number of characters such that there's no consecutive "R" and no consecutive "L".
So, if the input is like "LLLRLRR", then the output will be "LRLR"
To solve this, we will follow these steps −
- seen := first character of s
- ans := first character of s
- for each character i from index 1 to end of s, do
- if i is not same as seen, then
- ans := ans + i
- seen := i
- if i is not same as seen, then
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s): seen = s[0] ans = s[0] for i in s[1:]: if i != seen: ans += i seen = i return ans ob = Solution() print(ob.solve("LLLRLRR"))
Input
"LLLRLRR"
Output
LRLR
- Related Questions & Answers
- Remove Duplicates from Sorted Array in Python
- Remove All Adjacent Duplicates In String in Python
- Python - Ways to remove duplicates from list
- Remove all duplicates from a given string in Python
- Python program to remove Duplicates elements from a List?
- Remove array duplicates by property - JavaScript
- Remove duplicates from a List in C#
- Remove Duplicates from Sorted List in C++
- Merge and remove duplicates in JavaScript Array
- Removing consecutive duplicates from strings in an array using JavaScript
- How to remove duplicates from MongoDB Collection?
- Remove Duplicates from Sorted Array II in C++
- Remove Duplicates from Sorted List II in C++
- Remove duplicates and map an array in JavaScript
- Python program to remove all duplicates word from a given sentence.
Advertisements