LeetCode 748. Shortest Completing Word
考点 | 难度 |
---|---|
Hash Table | Easy |
题目
Given a string licensePlate
and an array of strings words, find the shortest completing word in words.
A completing word is a word that contains all the letters in licensePlate
. Ignore numbers and spaces in licensePlate
, and treat letters as case insensitive. If a letter appears more than once in licensePlate
, then it must appear in the word the same number of times or more.
For example, if licensePlate = "aBc 12c"
, then it contains letters ‘a’, ‘b’ (ignoring case), and ‘c’ twice. Possible completing words are “abccdef”, “caaacab”, and “cbca”.
Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.
思路
需要两个helper function:
1.把所有大写字母用小写字母代替
2.判断给定的string是否符合要求
第一个function用if + toLowerCase()
即可;
第二个function需要两个argument:第一个是licensePlate
,第二个是words
里面的string。首先还是新建一个——用来储存26个字母和出现的次数。第二步是遍历s2
的每一个字母,给对应的位置加一。最后遍历s1
的每一个字母,如果那个字母位置上是0直接返回false(说明s2
里不包括s1
里的所有字母),否则在字母对应的位置上减一。
现在已经可以筛选出符合条件的string了。对比所有string的长度,选出长度最短的一个就可以了。
答案
public String shortestCompletingWord(String licensePlate, String[] words) {
int minLen = Integer.MAX_VALUE;
int idx = -1;
String s = normalizeLetters(licensePlate);
for (int i = 0; i < words.length; i++) {
if (words[i].length() < minLen && isGoodMatch(s, words[i])) {
minLen = words[i].length();
idx = i;
}
}
return words[idx];
}
public String normalizeLetters(String s) {
StringBuilder builder = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 'A' && ch <= 'z')
builder.append(Character.toLowerCase(ch));
}
return builder.toString();
}
public boolean isGoodMatch(String s1, String s2) {
if (s1.length() > s2.length()) return false;
int[] letters = new int[26];
for (int i = 0; i < s2.length(); i++)
letters[s2.charAt(i) - 'a']++;
for (int j = 0; j < s1.length(); j++) {
if (letters[s1.charAt(j) - 'a'] == 0)
return false;
letters[s1.charAt(j) - 'a']--;
}
return true;
}