做法大致就是将每个字符对应的ASCII码-'a'
后存进数组,然后对照两个数组来求最优解。
import java.util.Locale;
//748. 最短补全词
public class ShortestCompletingWord {
public static void main(String[] args) {
String str="da A a54";
System.out.println(new ShortestCompletingWord().shortestCompletingWord("OgEu755",new String[]{"enough","these","play","wide","wonder","box","arrive","money","tax","thus"}));
}
public String shortestCompletingWord(String licensePlate, String[] words) {
String str="";
int bestsum=0;
int []arr=new int[26];
//将字符串变为小写,再将里面的数字和空格排除,然后将剩下的字符存入数组里
licensePlate=licensePlate.toLowerCase(Locale.ROOT);
for (int i = 0; i < licensePlate.length(); i++) {
if (licensePlate.charAt(i)>=97&&licensePlate.charAt(i)<=122){
arr[licensePlate.charAt(i)-'a']++;
}
}
//逐个遍历字符数组里的字符
for (int i = 0; i < words.length; i++) {
//创建/清空临时数组
int []arrnew=new int[26];
//将他的字符存入arrnew数组里
for (int i1 = 0; i1 < words[i].length(); i1++) {
arrnew[words[i].charAt(i1)-'a']++;
}
//设置开关,用来判断是否该字符串包含我们的licensePlate字符串里的字符
int bool=1;
//判断是否该字符串包含licensePlate字符串里的字符
for (int i1 = 0; i1 < arr.length; i1++)
//如果不包含将开关关闭,退出循环
if (arr[i1]>0) if (arrnew[i1]<arr[i1]) {
bool=0;
break;
}
//如果开关开着,判断和最有解比较,判断是否为最优解
if (bool==1) {
if(bestsum==0){
bestsum=words[i].length();
str=words[i];
}else {
if (words[i].length()<bestsum) {
bestsum=words[i].length();
str=words[i];
}
}
}
}
return str;
}
}
了解更多可以看将字符存入数组