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.
Example 4:
Input: s = "dDzeE" Output: "dD" Explanation: Both "dD" and "eE" are the longest nice substrings. As there are multiple longest nice substrings, return "dD" since it occurs earlier.
Constraints:
1 <= s.length <= 100
s
consists of uppercase and lowercase English letters.
官方建议:Brute force and check each substring to see if it is nice.
class Solution {
public String longestNiceSubstring(String s) {
int sl = s.length();
String answer = "";
for(int cut = 0; cut<=sl; cut++) {
if(cut == sl) {
break;
}else if(answer.length()>1){
break;
}
//开切
for(int i =0; i<=cut; i++) {
String str = s.substring(i, sl-(cut-i));
boolean tem = true;
boolean[] flag = new boolean[200];
for(int j =0; j<str.length(); j++) {
flag[str.charAt(j)] = true;
}
for(int k =65; k<=90; k++) {
if(flag[k]&&!flag[k+32]) {tem = false;}
}
for(int k =97; k<=122; k++) {
if(flag[k]&&!flag[k-32]) {tem = false;}
}
if(tem) {
answer = str;
break;
}
}
}
return answer;
}
}