Program to find longest nice substring using Python


Suppose we have a string s. We have to find longest nice substring of s. For a string s, it will be said to nice when, for every letter of the alphabet in s, it appears in uppercase and lowercase both. If there are multiple such substring, then return the substring of the earliest occurrence.

So, if the input is like s = "ZbybBbz", then the output will be "bBb" as this contains lowercase and uppercase B's.

To solve this, we will follow these steps −

  • cur_max:= -1

  • res:= blank string

  • for i in range 0 to size of s, do

    • c := s[i]

    • upper := a new set

    • lower := a new set

    • if c is in lowercase, then

      • add c into lower

    • if c is in uppercase, then

      • add c into upper but before convert it into lowercase

    • for j in range i+1 to size of s, do

      • c := s[j]

      • if c is in lowercase, then

        • add c into lower

      • if c is in uppercase, then

        • add c into upper but before convert it into lowercase

      • if upper is same as lower, then

        • if j-i > cur_max, then

          • cur_max := j-i

          • res := substring of s[from index i to j+1]

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(s):
   cur_max= -1
   res=""
   for i in range(len(s)):
      c = s[i]
      upper = set()
      lower = set()
      if c.islower():
         lower.add(c)
      if c.isupper():
         upper.add(c.lower())
      for j in range(i+1,len(s)):
         c = s[j]
         if c.islower():
            lower.add(c)
         if c.isupper():
            upper.add(c.lower())
         if upper == lower:
            if j-i>cur_max:
               cur_max = j-i
               res = s[i:j+1]
   return res
s = "ZbybBbz"
print(solve(s))

Input

"ZbybBbz"

Output

bBb

Updated on: 29-May-2021

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements