4.最短补全词
给你一个字符串 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中的 最短补全词 。
补全词 是一个包含 licensePlate 中所有字母的单词。
在匹配 licensePlate 中的字母时:
忽略 licensePlate 中的 数字和空格 。
不区分大小写。
如果某个字母在 licensePlate 中出现不止一次,那么该字母在补全词中的出现次数应当一致或者更多。
例如:licensePlate = “aBc 12c”,那么它的补全词应当包含字母 ‘a’、‘b’ (忽略大写)和两个 ‘c’ 。可能的 补全词 有 “abccdef”、“caaacab” 以及 “cbca” 。
请你找出并返回 words 中的 最短补全词 。题目数据保证一定存在一个最短补全词。当有多个单词都符合最短补全词的匹配条件时取 words 中 第一个 出现的那个。
示例 1:
输入:licensePlate = “1s3 PSt”, words = [“step”, “steps”, “stripe”, “stepple”]
输出:“steps”
解释:最短补全词应该包括 “s”、“p”、“s”(忽略大小写) 以及 “t”。
“step” 包含 “t”、“p”,但只包含一个 “s”,所以它不符合条件。
“steps” 包含 “t”、“p” 和两个 “s”。
“stripe” 缺一个 “s”。
“stepple” 缺一个 “s”。
因此,“steps” 是唯一一个包含所有字母的单词,也是本例的答案。
public String shortestCompletingWord(String licensePlate, String[] words) {
/**
* 首先去除licensePlate中所有的干扰字符
* 把licensePlate中所有的字符转化为小写,定义一个长为26的int型数组targetCharTime
* 按照字母顺序分别把licensePlate中各个字母的数量添加到targetCharTime中的对应索引位置
* 遍历words,定义一个长为26的int型数组charTime,把words中的的每个字符串的字母都按照字母顺序添加到charTime中的对应索引位置
* 遍历两个int型数组,分别比较各个索引的字母数量,若targetCharTime[i] < charTime[i],则这个字符串符合,把它记录到list中
* 再比较出list中最短的字符串,若有多个,去除最前面索引位置的字符串并返回
*/
List<String> strings = new ArrayList<String>();//记录words中所有符合题意的字符串
String stringss = null;//最终返回的字符串
int[] targetCharTime = new int[26];//记录licensePlate每个字母出现的次数
String newLicensePlate =
licensePlate.replaceAll("[\\d]|[\\s]","").toLowerCase();//使用正则去除干扰字符
//把licensePlate每个字母出现的次数记录到targetCharTime
for (int i = 0 ; i < newLicensePlate.length() ; i++){
int index = newLicensePlate.charAt(i) - 'a';
targetCharTime[index] += 1;
}
//遍历words
for(String s : words){
boolean f = true;//符合题意的标志
int[] charTime = new int[26];//记录words[i]中每个字母出现的次数
//把words[i]中每个字母出现的次数记录到harTime
for (int i = 0 ; i < s.length() ; i++){
int index = s.charAt(i) - 'a';
charTime[index] += 1;
}
//判断words[i]是否为符合题意的字符串
for (int i = 0 ; i < targetCharTime.length ; i++){
if (targetCharTime[i] > charTime[i]){
f = false;
break;
}
}
if (f == true){
strings.add(s);
}
}
int length = strings.get(0).length();//记录最短的符合题意的字符串的长度
//遍历list找出最短的字符串的长度
for(int i = 0 ; i < strings.size() ; i++){
if (i == strings.size()-1){
break;
}else {
if(length > strings.get(i+1).length()){
length = strings.get(i+1).length();
}
}
}
//找出最短且索引位置最小的字符串
for (String s : strings){
if(s.length() == length){
stringss = s;
break;
}
}
return stringss;
}