Leetcode 1763. Longest Nice Substring
Given a string s
, return the longest substring of s
that is a “nice” substring. A “nice” substring is a string where, for every letter in that substring, the corresponding uppercase or lowercase letter also exists in the substring. If there are multiple longest “nice” substrings, return the one that appears first. If there are none, return an empty string.
s
?Based on the prompt, I’ll assume:
s
is non-null.The solution to this problem can be approached using the following steps:
s
.For checking the “nice” property, we can use a set to record the presence of characters in both their uppercase and lowercase forms. If all characters in a substring have both their uppercase and lowercase counterparts, the substring is considered “nice”.
public class Solution {
public String longestNiceSubstring(String s) {
int n = s.length();
String longestNiceSubstring = "";
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
String substring = s.substring(i, j);
if (isNice(substring) && substring.length() > longestNiceSubstring.length()) {
longestNiceSubstring = substring;
}
}
}
return longestNiceSubstring;
}
private boolean isNice(String str) {
Set<Character> set = new HashSet<>();
for (char ch : str.toCharArray()) {
set.add(ch);
}
for (char ch : str.toCharArray()) {
if (!set.contains(Character.toUpperCase(ch)) || !set.contains(Character.toLowerCase(ch))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
String s = "YazaAay";
System.out.println("Longest Nice Substring: " + solution.longestNiceSubstring(s));
}
}
Combining these complexities, the overall time complexity is:
This is because for each of the ( \frac{n(n+1)}{2} \approx O(n^2) ) substrings, we are performing a (O(n)) check.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?