Longest Nice Substring — LeetCode 1763 Python Solution
EasyBit ManipulationHash TableStringDivide and ConquerSliding Window
- Problem
- #1763
- Pattern
- Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear.
Example
- Input
- s = "YazaAay"
- Output
- "aAa"
- Explanation
- "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.
Python solution
Python
class Solution:
def longestNiceSubstring(self, s: str) -> str:
n = len(s)
ans = ''
for i in range(n):
ss = set()
for j in range(i, n):
ss.add(s[j])
if (
all(c.lower() in ss and c.upper() in ss for c in ss)
and len(ans) < j - i + 1
):
ans = s[i : j + 1]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1763. Longest Nice Substring is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
LeetCode 187Repeated DNA SequencesMediumLeetCode 395Longest Substring with At Least K Repeating CharactersMediumLeetCode 1016Binary String With Substrings Representing 1 To NMediumLeetCode 3Longest Substring Without Repeating CharactersMediumLeetCode 30Substring with Concatenation of All WordsHardLeetCode 76Minimum Window SubstringHard
Frequently asked questions
- How hard is LeetCode 1763. Longest Nice Substring?
- LeetCode 1763. Longest Nice Substring is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1763. Longest Nice Substring?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1763. Longest Nice Substring?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1763. Longest Nice Substring cover?
- LeetCode 1763. Longest Nice Substring is tagged Bit Manipulation, Hash Table, String, Divide and Conquer and Sliding Window on LeetCode.