给出一个字符串数组 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”
提示:
1 <= words.length <= 1000
1 <= words[i].length <= 30
所有输入的字符串 words[i] 都只包含小写字母。
class Solution {Set<String> set = new HashSet<>();public String longestWord(String[] words) {for (String s : words) set.add(s);String res = "";for (String s : words) {if (s.length() >= res.length() && check(s)) {if (s.length() == res.length()) {//比较字典序String tem = "";for (int i = 0; i < s.length(); ++i)if (s.charAt(i) < res.charAt(i)) {tem = s;break;} else if (s.charAt(i) > res.charAt(i)) {tem = res;break;}res = tem;} else res = s;}}return res;}private boolean check(String s) {if (s.length() == 1 && set.contains(s)) return true;String tem = s.substring(0, s.length() - 1);boolean res = false;if (set.contains(tem))res = check(tem);return res;}}
前缀树
class Solution {class TreeNode {TreeNode[] node = new TreeNode[26];boolean isWord;}TreeNode root = new TreeNode();private void add(String s) {TreeNode p = root;for (int i = 0 ; i < s.length(); ++i) {int u = s.charAt(i) - 'a';if (p.node[u] == null) p.node[u] = new TreeNode();p = p.node[u];}//标记结尾p.isWord = true;}public String longestWord(String[] words) {for (String s : words) add(s);String res = "";for (String s : words) {int n = res.length(), m = s.length();if (m < n) continue;if (m == n && s.compareTo(res) > 0) continue;if (search(s)) res = s;}return res;}private boolean search(String s) {TreeNode p = root;for (int i = 0; i < s.length(); ++i) {int tem = s.charAt(i) - 'a';if (p.node[tem] == null || p.node[tem].isWord == false)return false;p = p.node[tem];}return p != null && p.isWord;}}
