共计 2345 个字符,预计需要花费 6 分钟才能阅读完成。
序
本文次要记录一下 leetcode 之最短补全词
题目
给定一个字符串牌照 licensePlate 和一个字符串数组 words,请你找出并返回 words 中的 最短补全词。如果单词列表(words)中的一个单词蕴含牌照(licensePlate)中所有的字母,那么咱们称之为 补全词。在所有残缺词中,最短的单词咱们称之为 最短补全词。单词在匹配牌照中的字母时要:疏忽牌照中的数字和空格。不辨别大小写,比方牌照中的 "P" 仍然能够匹配单词中的 "p" 字母。如果某个字母在牌照中呈现不止一次,那么该字母在补全词中的呈现次数该当统一或者更多。例如:licensePlate = "aBc 12c",那么它由字母 'a'、'b'(疏忽大写)和两个 'c'。可能的 补全词 是 "abccdef"、"caaacab" 以及 "cbca"。题目数据保障肯定存在一个最短补全词。当有多个单词都合乎最短补全词的匹配条件时取单词列表中最靠前的一个。示例 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" 是惟一一个蕴含所有字母的单词,也是本样例的答案。示例 2:输出:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"]
输入:"pest"
阐明:存在 3 个蕴含字母 "s" 且有着最短长度的补全词,"pest"、"stew"、和 "show" 三者长度雷同,但咱们返回最先呈现的补全词 "pest"。示例 3:输出:licensePlate = "Ah71752", words = ["suggest","letter","of","husband","easy","education","drug","prevent","writer","old"]
输入:"husband"
示例 4:输出:licensePlate = "OgEu755", words = ["enough","these","play","wide","wonder","box","arrive","money","tax","thus"]
输入:"enough"
示例 5:输出:licensePlate = "iMSlpe4", words = ["claim","consumer","student","camera","public","never","wonder","simple","thought","use"]
输入:"simple"
提醒:1 <= licensePlate.length <= 7
licensePlate 由数字、大小写字母或空格 ' ' 组成
1 <= words.length <= 1000
1 <= words[i].length <= 15
words[i] 由小写英文字母组成
起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/shortest-completing-word
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
题解
class Solution {public String shortestCompletingWord(String licensePlate, String[] words) {Map<Character,Integer> charCountMap = new HashMap<>();
for(Character c : licensePlate.toCharArray()) {if (Character.isLetter(c)) {char lower = Character.toLowerCase(c);
charCountMap.put(lower, charCountMap.getOrDefault(lower, 0) + 1);
}
}
Integer length = null;
String result = null;
for(String word : words) {Map<Character,Integer> tmpMap = new HashMap<>();
for (Character c : word.toCharArray()) {char lower = Character.toLowerCase(c);
tmpMap.put(lower, tmpMap.getOrDefault(lower, 0) + 1);
}
boolean matched = true;
for (Map.Entry<Character,Integer> entry : charCountMap.entrySet()) {int c = tmpMap.getOrDefault(entry.getKey(), 0);
if (c < entry.getValue()) {
matched = false;
break;
}
}
if (matched && (length == null || length > word.length())) {
result = word;
length = word.length();}
}
return result;
}
}
小结
这里就暴力求解,先统计 licensePlate 中字母的个数;之后遍历 words,挨个统计每个 word 的字母个数,而后去校验是否蕴含 licensePlate 中的字母以及个数是否相符,最初在对合乎的 word 的长度进行判断,取最短的,如果都一样取最先呈现的。
doc
- 最短补全词
正文完