1763. Longest Nice Substring
Explanation
To find the longest nice substring in a given string, we can iterate through all possible substrings of the input string and check if each substring is nice. We can do this by iterating over each character of the substring and keeping track of the uppercase and lowercase characters that appear in that substring. If for every letter that appears in the substring, both uppercase and lowercase versions are present, then it is a nice substring.
We start with the longest possible substring and gradually decrease its length until we find a nice substring. We can use a nested loop to generate all possible substrings efficiently. The time complexity of this approach is O(n^3) where n is the length of the input string.
class Solution {
public String longestNiceSubstring(String s) {
String res = "";
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length(); j++) {
String sub = s.substring(i, j + 1);
if (isNice(sub) && sub.length() > res.length()) {
res = sub;
}
}
}
return res;
}
private boolean isNice(String s) {
boolean[] upper = new boolean[26];
boolean[] lower = new boolean[26];
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c)) {
upper[c - 'A'] = true;
} else {
lower[c - 'a'] = true;
}
}
for (int i = 0; i < 26; i++) {
if (upper[i] != lower[i]) {
return false;
}
}
return true;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.