题目
如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。
单词在匹配牌照中的字母时不区分大小写,比如牌照中的 “P” 依然可以匹配单词中的 “p” 字母。
我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。
牌照中可能包含多个相同的字符,比如说:对于牌照 “PP”,单词 “pair” 无法匹配,但是 “supper” 可以匹配。
题解一(个人)
思路: 把licensePlate转换成小写,先用一个数组统计licensePlate中的各个字母个数,然后统计word每一个单词中各个字母个数。当前者的某个字母个数小于等于后者某个单词的该字母个数并且这个单词长度更短时就更新,否则跳到下一个单词。
时间: 26ms
代码:
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
licensePlate=licensePlate.toLowerCase();
int[] map=new int[127];
String res="";
for(int i=0;i<licensePlate.length();i++){
if(licensePlate.charAt(i)>='a'&&licensePlate.charAt(i)<='z'){
map[licensePlate.charAt(i)]++;
}
}
outer:
for(int i=0;i<words.length;i++){
int[] temp=new int[127];
for(int j=0;j<words[i].length();j++){
temp[words[i].charAt(j)]++;
}
for(int j=0;j<map.length;j++){
if(temp[j]<map[j])continue outer;
}
if(res.length()==0)res=words[i];
else
res=(res.length()<=words[i].length()?res:words[i]);
}
return res;
}
}
题解二(leetcode优解)
思路相似,但是实现细节更优
时间: 7ms
代码:
class Solution {
public String shortestCompletingWord(String licensePlate, String[] words) {
int[] lp = new int[26];
for (int i =0;i<licensePlate.length();i++)
{
char ch = licensePlate.charAt(i);
if (ch>=65 && ch<=90)
{
ch = (char) (ch + 32);
}
if (ch>=97 && ch<=122)
{
lp[ch-97]++;
}
}
int cnt = Integer.MAX_VALUE;
String res = null;
for (String word : words)
{
if (isComplete(word,lp))
{
if (cnt>word.length())
{
cnt = word.length();
res = word;
}
}
}
return res;
}
static boolean isComplete(String word , int [] lp)
{
int [] wcnt = new int[26];
char[] chars = word.toCharArray();
for (char ch : chars)
{
wcnt[ch-97]++;
}
for (int i = 0;i<lp.length;i++)
{
if (lp[i]>wcnt[i])
{
return false;
}
}
return true;
}
}