
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find String After Deleting K Consecutive Duplicate Characters in Python
Suppose we have a string s and another value k, we repeatedly delete the earliest k consecutive duplicate characters, and return the final string.
So, if the input is like s = "paaappmmmma" k = 3, then the output will be "ma", as when we delete three "a"s to get "pppmmmma". Then we delete three "p"s to get "mmmma". Then delete three of the four "m"s to get "ma".
To solve this, we will follow these steps:
- do the following steps infinitely, do
- count := 0
- chars := get the unique characters from s
- for each character c in chars, do
- if k consecutive c is in s, then
- delete k consecutive c from s
- count := count + 1
- if k consecutive c is in s, then
- if count is same as 0, then
- come out from the loop
- returns
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, s, k): while True: count = 0 chars = set(s) for c in chars: if c * k in s: s = s.replace(c * k, "") count += 1 if count == 0: break return s ob = Solution() s = "paaappmmmma" k = 3 print(ob.solve(s, k))
Input
"paaappmmmma", 3
Output
ma
Advertisements