Program to find a good string from a given string in Python

PythonServer Side ProgrammingProgramming

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 −

 Live Demo

def solve(s):
   res = []
   for ch in s:
      if res and res[-1] != ch and res[-1].lower() == ch.lower():
   return ''.join(res)

s = "popPpulaBbr"




Published on 17-May-2021 12:28:03