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. However, "abA"
is not because 'b'
appears, but 'B'
does not.
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.
Example 1:
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. "aAa" is the longest nice substring.
Example 2:
Input: s = "Bb" Output: "Bb" Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.
Example 3:
Input: s = "c" Output: "" Explanation: There are no nice substrings.
Constraints:
1 <= s.length <= 100
s
consists of uppercase and lowercase English letters.
class Solution:
def longestNiceSubstring(self, s: str) -> str:
n = len(s)
ans = ''
for i in range(n):
lower = upper = 0
for j in range(i, n):
if s[j].islower():
lower |= 1 << (ord(s[j]) - ord('a'))
else:
upper |= 1 << (ord(s[j]) - ord('A'))
if lower == upper and j - i + 1 > len(ans):
ans = s[i : j + 1]
return ans
class Solution {
public String longestNiceSubstring(String s) {
int n = s.length();
String ans = "";
for (int i = 0; i < n; ++i) {
int lower = 0, upper = 0;
for (int j = i; j < n; ++j) {
char c = s.charAt(j);
if (Character.isLowerCase(c)) {
lower |= 1 << (c - 'a');
} else {
upper |= 1 << (c - 'A');
}
if (lower == upper && j - i + 1 > ans.length()) {
ans = s.substring(i, j + 1);
}
}
}
return ans;
}
}
function longestNiceSubstring(s: string): string {
const n = s.length;
let ans = '';
for (let i = 0; i < n; i++) {
let lower = 0,
upper = 0;
for (let j = i; j < n; j++) {
const c = s.charCodeAt(j);
if (c > 96) {
lower |= 1 << (c - 97);
} else {
upper |= 1 << (c - 65);
}
if (lower == upper && j - i + 1 > ans.length) {
ans = s.substring(i, j + 1);
}
}
}
return ans;
}
class Solution {
public:
string longestNiceSubstring(string s) {
int n = s.size();
string ans = "";
for (int i = 0; i < n; ++i) {
int lower = 0, upper = 0;
for (int j = i; j < n; ++j) {
if (islower(s[j]))
lower |= 1 << (s[j] - 'a');
else
upper |= 1 << (s[j] - 'A');
if (lower == upper && j - i + 1 > ans.size()) ans = s.substr(i, j - i + 1);
}
}
return ans;
}
};
func longestNiceSubstring(s string) (ans string) {
for i := range s {
lower, upper := 0, 0
for j := i; j < len(s); j++ {
if unicode.IsLower(rune(s[j])) {
lower |= 1 << (s[j] - 'a')
} else {
upper |= 1 << (s[j] - 'A')
}
if lower == upper && j-i+1 > len(ans) {
ans = s[i : j+1]
}
}
}
return
}