1873. Longest Nice Substring
My accepted Python solution to LeetCode problem 1873, Longest Nice Substring, running in 0ms.
- Difficulty: Easy
- Python
- Runtime 0ms
- Memory 17.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 0ms, memory 17.1MB, accepted 2025-12-29.
class Solution:
def longestNiceSubstring(self, s: str) -> str:
# Divide and conquer: split on bad chars
# Time: O(n^2), Space: O(n)
if len(s) < 2:
return ""
char_set = set(s)
for i, c in enumerate(s):
if c.swapcase() not in char_set:
# Split at this position
left = self.longestNiceSubstring(s[:i])
right = self.longestNiceSubstring(s[i+1:])
return left if len(left) >= len(right) else right
return s # Whole string is nice