image.png

    字典树(前缀树)

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