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