leetcode 链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/

题目

image.png

解法

题目限定了字母为小写字母 a-z,所以可以创建一个大小为 26 的数组,每个数组位置代表一个字母

  1. public class Trie {
  2. // 根节点
  3. private final Node root;
  4. private class Node {
  5. private static final int size = 26;
  6. // 当前节点是否为某个单词的末位
  7. boolean isWord;
  8. // 指向子节点
  9. Node[] next;
  10. public Node(boolean isWord) {
  11. this.isWord = isWord;
  12. next = new Node[size];
  13. }
  14. public Node() {
  15. this(false);
  16. }
  17. public boolean containsKey(char ch) {
  18. return next[ch - 'a'] != null;
  19. }
  20. public Node get(char ch) {
  21. return next[ch - 'a'];
  22. }
  23. public void put(char ch, Node node) {
  24. next[ch - 'a'] = node;
  25. }
  26. }
  27. public Trie() {
  28. this.root = new Node();
  29. }
  30. /**
  31. * Inserts a word into the trie.
  32. */
  33. public void insert(String word) {
  34. Node curr = root;
  35. for (int i = 0; i < word.length(); i++) {
  36. char ch = word.charAt(i);
  37. if (!curr.containsKey(ch)) {
  38. curr.put(ch, new Node());
  39. }
  40. curr = curr.get(ch);
  41. }
  42. curr.isWord = true;
  43. }
  44. /**
  45. * Returns if the word is in the trie.
  46. */
  47. public boolean search(String word) {
  48. Node curr = root;
  49. for (int i = 0; i < word.length(); i++) {
  50. char ch = word.charAt(i);
  51. if (!curr.containsKey(ch)) {
  52. return false;
  53. }
  54. curr = curr.get(ch);
  55. }
  56. return curr.isWord;
  57. }
  58. /**
  59. * Returns if there is any word in the trie that starts with the given prefix.
  60. */
  61. public boolean startsWith(String prefix) {
  62. Node curr = root;
  63. for (int i = 0; i < prefix.length(); i++) {
  64. char ch = prefix.charAt(i);
  65. if (!curr.containsKey(ch)) {
  66. return false;
  67. }
  68. curr = curr.get(ch);
  69. }
  70. return true;
  71. }
  72. }