题目

Implement a trie with insert, search, and startsWith methods.

Example:

  1. Trie trie = new Trie();
  2. trie.insert("apple");
  3. trie.search("apple"); // returns true
  4. trie.search("app"); // returns false
  5. trie.startsWith("app"); // returns true
  6. trie.insert("app");
  7. trie.search("app"); // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

题意

实现字典树。

思路

每个结点最多可以有26个子结点,同时给每个结点设置一个标志位用来指明当前结点是否为一个单词的结尾。


代码实现

Java

  1. class Trie {
  2. private Node root;
  3. /** Initialize your data structure here. */
  4. public Trie() {
  5. root = new Node();
  6. }
  7. /** Inserts a word into the trie. */
  8. public void insert(String word) {
  9. Node p = root;
  10. for (char c : word.toCharArray()) {
  11. if (p.children[c - 'a'] == null) {
  12. p.children[c - 'a'] = new Node();
  13. }
  14. p = p.children[c - 'a'];
  15. }
  16. p.end = true;
  17. }
  18. /** Returns if the word is in the trie. */
  19. public boolean search(String word) {
  20. Node p = prefix(word);
  21. return p != null && p.end;
  22. }
  23. /**
  24. * Returns if there is any word in the trie that starts with the given prefix.
  25. */
  26. public boolean startsWith(String prefix) {
  27. return prefix(prefix) != null;
  28. }
  29. private Node prefix(String word) {
  30. Node p = root;
  31. for (char c : word.toCharArray()) {
  32. if (p.children[c - 'a'] == null) {
  33. return null;
  34. }
  35. p = p.children[c - 'a'];
  36. }
  37. return p;
  38. }
  39. }
  40. class Node {
  41. Node[] children = new Node[26];
  42. boolean end;
  43. }