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.
这题要求一个string里最长的substring,这个substring要满足的条件是里面的每一个char都同时有大小写出现。直观的想法就是双重for loop遍历所有的substring,每个substring看看是不是每个字符的大小写都出现在substring里。知道肯定有更好的解法但是想不到,看了答案以后惊觉这是divide and conquer。怎么想到d/c的呢,借鉴- LeetCode,大概是因为如果中间有一个字母不满足条件的话,只能查找它前后的substring了。
所以知道了思路以后其实很简单,先用一个set把所有char存进去,然后针对当前要check的string,从头到尾遍历,如果遇到一个字符它并没有大小写都出现,那就把它分成前后两部分分别求他们的longest nice substring,最后取前后两个里面更长的那个作为结果。
class Solution {
public String longestNiceSubstring(String s) {
if (s.length() < 2) {
return "";
}
Set<Character> chars = new HashSet<>();
for (char c : s.toCharArray()) {
chars.add(c);
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (chars.contains(Character.toLowerCase(c)) && chars.contains(Character.toUpperCase(c))) {
continue;
}
String leftNiceSubstring = longestNiceSubstring(s.substring(0, i));
String rightNiceSubstring = longestNiceSubstring(s.substring(i + 1, s.length()));
return leftNiceSubstring.length() >= rightNiceSubstring.length() ? leftNiceSubstring : rightNiceSubstring;
}
return s;
}
}