题目来源:
leetcode题目,网址:1763. 最长的美好子字符串 - 力扣(LeetCode)
解题思路:
暴力遍历判断即可。
解题代码:
class Solution {
public String longestNiceSubstring(String s) {
for(int length=s.length();length>0;length--){
for(int i=0;i+length<=s.length();i++){
if(isNiceString(s.substring(i,i+length))){
return s.substring(i,i+length);
}
}
}
return "";
}
public boolean isNiceString(String s){
int[][] count=new int[26][2];
for(int i=0;i<s.length();i++){
char temp=s.charAt(i);
if(Character.isUpperCase(temp)){
count[temp-'A'][1]++;
}else{
count[temp-'a'][0]++;
}
}
for(int i=0;i<count.length;i++){
if(( (count[i][0]==0) && (count[i][1]>0) ) || ((count[i][1]==0)&&(count[i][0]>0))){
return false;
}
}
return true;
}
}
总结:
官方题解给出了三种解法。
第一种是枚举,不过他是利用二进制位标记。
第二种是分治,递归字符串时首先判断该字符串是否是完美字符串,若是,直接返回,否则找出该字符串内既有大写又有小写的字符集 set ,接着找出该字符串内只有 set 集内字符的子字符串进行递归处理。
第三种是滑动窗口。首先获取字符串中的字符种类数(不区分大小写) x ,然后使用滑动窗口依次获得当窗口内字符种类数(不区分大小写)为 1,2,3......x 时的最长完美子字符串长度,最后返回其中最长的完美字符串即可。窗口的滑动,若窗口内字符种类数小于等于给定的字符种类数(1,2,3......x),右边窗口向右滑动,否则左边窗口向右滑动。