题目描述
如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。
单词在匹配牌照中的字母时不区分大小写,比如牌照中的 “P” 依然可以匹配单词中的 “p” 字母。
我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。
牌照中可能包含多个相同的字符,比如说:对于牌照 “PP”,单词 “pair” 无法匹配,但是 “supper” 可以匹配。
示例 1:
输入:licensePlate = “1s3 PSt”, words = [“step”, “steps”, “stripe”, “stepple”]
输出:“steps”
说明:最短完整词应该包括 “s”、“p”、“s” 以及 “t”。对于 “step” 它只包含一个 “s” 所以它不符合条件。同时在匹配过程中我们忽略牌照中的大小写。
示例 2:
输入:licensePlate = “1s3 456”, words = [“looks”, “pest”, “stew”, “show”]
输出:“pest”
说明:有三个单词都符合完整词的定义,但是我们返回最先出现的单词。
注意:
牌照(licensePlate)的长度在区域[1, 7]中。
牌照(licensePlate)将会包含数字、空格、或者字母(大写和小写)。
单词列表(words)长度在区间 [10, 1000] 中。
每一个单词 words[i] 都是小写,并且长度在区间 [1, 15] 中。
一开始想复杂了,一位ee等需要是必须连在一起的,搞错了,哎,还想的那么复杂
代码:我这个也很复杂,排名不是很靠前
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
//首先转成小写,然后放入set中,之后进行判断
licensePlate = licensePlate.toLowerCase();
System.out.println(licensePlate);
List<String> temList = new ArrayList<>();
int start = 0;
for (int i = 0; i < licensePlate.length() ; i++) {
if(licensePlate.charAt(i)<='z' && licensePlate.charAt(i) >= 'a'){
temList.add(licensePlate.substring(i,i+1));
}
}
System.out.println(temList.toString());
//将符合条件的都放入temmap中
List<String> temMap = new ArrayList();
int len = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
String string = words[i];
//遍历set集合
boolean flag = false;
for(String value: temList){
if(string.indexOf(value) != -1){
string = string.replaceFirst(value, " ");
continue;
}else {
flag = true;
break;
}
}
if(!flag){
len = Math.min(len, words[i].length());
temMap.add(words[i]);
}
}
System.out.println(temMap.toString());
//遍历hashmap,返回最先的那个
for (String string : temMap) {
if(string.length() == len){
return string;
}
}
return "";
}
}
排名靠前的代码
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
int[] licensePlateArr = new int[26];
licensePlate = licensePlate.toLowerCase();
for (int i = 0; i < licensePlate.length(); i++) {
if (Character.isLetter(licensePlate.charAt(i)))
licensePlateArr[licensePlate.charAt(i) - 'a']++;
}
String res = null;
// 遍历查看words是否包含licensePlate
for (int i = 0; i < words.length; i++) {
if (isContain(licensePlateArr, words[i])) {
if ((res == null) || (res != null && res.length() > words[i].length())) {
res = words[i];
}
}
}
return res;
}
/**
*
* @param licensePlate
* @param word
* @return
*/
public boolean isContain(int[] licensePlate, String word) {
int[] wordArr = new int[26];
for (int i = 0; i < word.length(); i++) {
wordArr[word.charAt(i) - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (licensePlate[i] > wordArr[i]) {
return false;
}
}
return true;
}
}