208. 实现 Trie (前缀树)

image.png

题解

执行用时:42 ms, 在所有 Java 提交中击败了60.29%的用户 内存消耗:47.1 MB, 在所有 Java 提交中击败了91.73%的用户

  1. class Trie {
  2. private Node root;
  3. private static class Node {
  4. // 当前字符
  5. char c;
  6. // 当前字符是否可构成一个单词
  7. boolean isWord;
  8. // 树的分支
  9. Node[] childedList;
  10. public Node(char c) {
  11. this.c = c;
  12. this.isWord = false;
  13. this.childedList = new Node[26];
  14. }
  15. }
  16. /** Initialize your data structure here. */
  17. public Trie() {
  18. // 树根初使化为一个空字符
  19. this.root = new Node(' ');
  20. }
  21. /** Inserts a word into the trie. */
  22. public void insert(String word) {
  23. int length = word.length();
  24. Node cur = root;
  25. for (int i = 0; i < length; i++) {
  26. char curChar = word.charAt(i);
  27. if (cur.childedList[curChar - 'a'] == null) {
  28. cur.childedList[curChar - 'a'] = new Node(curChar);
  29. }
  30. cur = cur.childedList[curChar - 'a'];
  31. }
  32. cur.isWord = true;
  33. }
  34. /** Returns if the word is in the trie. */
  35. public boolean search(String word) {
  36. Node node = searchReturnNode(word);
  37. if (node == null) {
  38. return false;
  39. }
  40. return node.isWord;
  41. }
  42. /** Returns if there is any word in the trie that starts with the given prefix. */
  43. public boolean startsWith(String prefix) {
  44. Node node = searchReturnNode(prefix);
  45. return node != null;
  46. }
  47. // 返回一个节点,可以给 search 和 startsWith 方法复用
  48. private Node searchReturnNode(String word) {
  49. Node cur = root;
  50. for (int i = 0; i < word.length(); i++) {
  51. char curChar = word.charAt(i);
  52. if (cur.childedList[curChar - 'a'] != null) {
  53. cur = cur.childedList[curChar - 'a'];
  54. } else {
  55. return null;
  56. }
  57. }
  58. return cur;
  59. }
  60. }