![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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
Advertisements