
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 a Good String from a Given String in Python
Suppose we have a string s with lower and upper case English letters. We shall consider a string is a good string which does not have any two adjacent characters s[i] and s[i + 1] where −
0 <= i <= size of s - 2
s[i] is in lower-case and s[i + 1] is the same letter but in upper-case or vice-versa.
To convert a string into good string, we can select two adjacent characters that make the string bad and remove them. We shall continue this process until the string becomes good, (An empty string can be a good one). We have to find the string after making it good.
So, if the input is like s = "popPpulaBbr", then the output will be "popular", because at first either delete "pP" or "Pp" and delete "Bb".
To solve this, we will follow these steps −
res := a new list
-
for each character ch in s, do
-
if res is not empty and last element in res is same as ch in any case upper or lower, then
delete last element from res
-
otherwise,
insert ch at the end of res
-
join each element present in res and return it
Example (Python)
Let us see the following implementation to get better understanding −
def solve(s): res = [] for ch in s: if res and res[-1] != ch and res[-1].lower() == ch.lower(): res.pop() else: res.append(ch) return ''.join(res) s = "popPpulaBbr" print(solve(s))
Input
"popPpulaBbr"
Output
popular