# Program to find longest nice substring using Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

• 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

• 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():
if c.isupper():
for j in range(i+1,len(s)):
c = s[j]
if c.islower():
if c.isupper():
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 14:32:57