
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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 Articles
- 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
- How do you remove duplicates from a list in Python?
- Python program to remove Duplicates elements from a List?
- Merge and remove duplicates in JavaScript Array
- Remove duplicates from a List in C#
- Remove Duplicates from Sorted List in C++
- Removing consecutive duplicates from strings in an array using JavaScript
- Python program to remove all duplicates word from a given sentence.
- Program to count operations to remove consecutive identical bits in Python
- Remove array duplicates by property - JavaScript
- Remove Duplicates from Sorted Array II in C++
- Remove Duplicates from Sorted List II in C++

Advertisements