
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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
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
- Related Questions & Answers
- Program to find longest awesome substring in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest consecutively increasing substring in Python
- Python Program to Find Longest Common Substring using Dynamic Programming with Bottom-Up Approach
- Program to find longest substring of all vowels in order in Python
- Program to print the longest common substring using C++
- Program to find length of longest common substring in C++
- Program to find length of longest palindromic substring after single rotation in Python
- Program to find length of longest substring with even vowel counts in Python
- Program to find length of longest repeating substring in a string in Python
- Longest Palindromic Substring in Python
- Find longest consecutive letter and digit substring in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Longest Palindromic Substring
- Program to find the length of longest substring which has two distinct elements in Python