#1763
Easy Algorithms Longest nice substring
Hash Table String Divide and Conquer Bit Manipulation Sliding Window
63.8% acceptance
Feb 25, 2026
1506
973
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase.
Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn longest_nice_substring(s: String) -> String {
let s = s.as_bytes();
let n = s.len();
let mut best_start = 0;
let mut best_len = 0;
for i in 0..n {
let mut lower = 0u32;
let mut upper = 0u32;
for j in i..n {
let c = s[j];
if c.is_ascii_lowercase() {
lower |= 1 << (c - b'a');
} else {
upper |= 1 << (c - b'A');
}
if lower == upper && j - i + 1 > best_len {
best_len = j - i + 1;
best_start = i;
}
}
}
String::from_utf8(s[best_start..best_start + best_len].to_vec()).unwrap()
}
}