leetcode 720. Longest Word in Dictionary | 720. 词典中最长的单词(Trie前缀树)

x33g5p2x  于2021-11-17 转载在 其他  
字(0.9k)|赞(0)|评价(0)|浏览(262)

题目

https://leetcode.com/problems/longest-word-in-dictionary/

题解

建立一个 Trie,在 insert 的过程中,除最后一个节点外,如果一路上每一个节点都 isEnd,则将其返回值 diff 设置为 false,表明它的差异可以被容忍,可参与最后的长度比较。

  1. class Node {
  2. Node[] map;
  3. boolean isEnd;
  4. public Node() {
  5. this.map = new Node['z' - 'a' + 1];
  6. }
  7. public Node get(char c) {
  8. return map[c - 'a'];
  9. }
  10. public Node put(char c) {
  11. Node node = new Node();
  12. map[c - 'a'] = node;
  13. return node;
  14. }
  15. }
  16. class Trie {
  17. Node node;
  18. public Trie() {
  19. node = new Node();
  20. }
  21. public boolean insert(String word) {
  22. char[] chars = word.toCharArray();
  23. Node cur = node;
  24. boolean diff = false;
  25. for (int i = 0; i < chars.length; i++) {
  26. if (cur.get(chars[i]) != null) {
  27. cur = cur.get(chars[i]);
  28. if (!cur.isEnd) diff = true;
  29. } else {
  30. cur = cur.put(chars[i]);
  31. if (i != word.length() - 1) diff = true;
  32. }
  33. if (i == chars.length - 1) cur.isEnd = true;
  34. }
  35. return diff;
  36. }
  37. }
  38. class Solution {
  39. public String longestWord(String[] words) {
  40. Arrays.sort(words);
  41. Trie trie = new Trie();
  42. String result = "";
  43. for (String word : words) {
  44. if (!trie.insert(word)) result = word.length() > result.length() ? word : result;
  45. }
  46. return result;
  47. }
  48. }

相关文章