题目
给出一个字符串数组 words 组成的一本英语词典。返回 words 中最长的一个单词,该单词是由 words 词典中其他单词逐步添加一个字母组成。
若其中有多个可行的答案,则返回答案中字典序最小的单词。若无答案,则返回空字符串。
示例 1:
输入:words = ["w","wo","wor","worl", "world"]
输出:"world"
解释: 单词"world"可由"w", "wo", "wor", 和 "worl"逐步添加一个字母组成。
示例 2:
输入:words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出:"apple"
解释:"apply" 和 "apple" 都能由词典中的单词组成。但是 "apple" 的字典序小于 "apply"
代码
/**
* 720. 词典中最长的单词
*
* @author peove
* @date 2022-03-17-9:16
*/
public class E720 {
public String longestWord(String[] words) {
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < words.length; i++) {
map.put(words[i], i);
}
String res = "";
for (int i = 0; i < words.length; i++) {
String word = words[i];
if ((word.length() > res.length() || word.length() == res.length() && word.compareTo(res) < 0) && getSub(word, map)) res = word;
}
return res;
}
public boolean getSub(String word, Map<String, Integer> map) {
String s = "";
for (int i = 0; i < word.length() - 1; i++) {
s = s.concat(String.valueOf(word.charAt(i)));
if (map.get(s) == null) return false;
}
return true;
}
public static void main(String[] args) {
E720 o = new E720();
String[] words = {"a", "banana", "app", "appl", "ap", "apply", "apple"}; // apple
String[] wordsA = {"b","br","bre","brea","break","breakf","breakfa","breakfas","breakfast","l","lu","lun","lunc","lunch","d","di","din","dinn","dinne","dinner"};
System.out.println(o.longestWord(words));
System.out.println(o.longestWord(wordsA));
}
}
附:测试图
来源
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary