给出一个字符串数组 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] 都只包含小写字母。


  1. class Solution {
  2. Set<String> set = new HashSet<>();
  3. public String longestWord(String[] words) {
  4. for (String s : words) set.add(s);
  5. String res = "";
  6. for (String s : words) {
  7. if (s.length() >= res.length() && check(s)) {
  8. if (s.length() == res.length()) {
  9. //比较字典序
  10. String tem = "";
  11. for (int i = 0; i < s.length(); ++i)
  12. if (s.charAt(i) < res.charAt(i)) {
  13. tem = s;
  14. break;
  15. } else if (s.charAt(i) > res.charAt(i)) {
  16. tem = res;
  17. break;
  18. }
  19. res = tem;
  20. } else res = s;
  21. }
  22. }
  23. return res;
  24. }
  25. private boolean check(String s) {
  26. if (s.length() == 1 && set.contains(s)) return true;
  27. String tem = s.substring(0, s.length() - 1);
  28. boolean res = false;
  29. if (set.contains(tem))
  30. res = check(tem);
  31. return res;
  32. }
  33. }

前缀树

  1. class Solution {
  2. class TreeNode {
  3. TreeNode[] node = new TreeNode[26];
  4. boolean isWord;
  5. }
  6. TreeNode root = new TreeNode();
  7. private void add(String s) {
  8. TreeNode p = root;
  9. for (int i = 0 ; i < s.length(); ++i) {
  10. int u = s.charAt(i) - 'a';
  11. if (p.node[u] == null) p.node[u] = new TreeNode();
  12. p = p.node[u];
  13. }
  14. //标记结尾
  15. p.isWord = true;
  16. }
  17. public String longestWord(String[] words) {
  18. for (String s : words) add(s);
  19. String res = "";
  20. for (String s : words) {
  21. int n = res.length(), m = s.length();
  22. if (m < n) continue;
  23. if (m == n && s.compareTo(res) > 0) continue;
  24. if (search(s)) res = s;
  25. }
  26. return res;
  27. }
  28. private boolean search(String s) {
  29. TreeNode p = root;
  30. for (int i = 0; i < s.length(); ++i) {
  31. int tem = s.charAt(i) - 'a';
  32. if (p.node[tem] == null || p.node[tem].isWord == false)
  33. return false;
  34. p = p.node[tem];
  35. }
  36. return p != null && p.isWord;
  37. }
  38. }