208. 实现 Trie (前缀树)

  1. class Trie {
  2. class TrieNode {
  3. public TrieNode[] children;
  4. public boolean isEnd;
  5. public TrieNode() {
  6. children = new TrieNode[26];
  7. isEnd = false;
  8. }
  9. }
  10. private TrieNode root;
  11. /** Initialize your data structure here. */
  12. public Trie() {
  13. root = new TrieNode();
  14. }
  15. /** Inserts a word into the trie. */
  16. public void insert(String word) {
  17. TrieNode node = root;
  18. if (word == null)
  19. return;
  20. char[] words = word.toCharArray();
  21. for (char ch : words) {
  22. if (node.children[ch - 'a'] == null)
  23. node.children[ch - 'a'] = new TrieNode();
  24. node = node.children[ch - 'a'];
  25. }
  26. node.isEnd = true;
  27. }
  28. /** Returns if the word is in the trie. */
  29. public boolean search(String word) {
  30. TrieNode node = root;
  31. if (word == null || word.length() == 0)
  32. return true;
  33. char[] words = word.toCharArray();
  34. for (char ch : words) {
  35. if (node.children[ch - 'a'] == null)
  36. return false;
  37. node = node.children[ch - 'a'];
  38. }
  39. return node.isEnd;
  40. }
  41. /** Returns if there is any word in the trie that starts with the given prefix. */
  42. public boolean startsWith(String prefix) {
  43. TrieNode node = root;
  44. if (prefix == null || prefix.length() == 0)
  45. return true;
  46. char[] pres = prefix.toCharArray();
  47. for (char ch : pres) {
  48. if (node.children[ch - 'a'] == null)
  49. return false;
  50. node = node.children[ch - 'a'];
  51. }
  52. return true;
  53. }
  54. }
  55. /**
  56. * Your Trie object will be instantiated and called as such:
  57. * Trie obj = new Trie();
  58. * obj.insert(word);
  59. * boolean param_2 = obj.search(word);
  60. * boolean param_3 = obj.startsWith(prefix);
  61. */