当前位置:   article > 正文

Java | Leetcode Java题解之第208题实现Trie(前缀树)

Java | Leetcode Java题解之第208题实现Trie(前缀树)

题目:

题解:

  1. class Trie {
  2. private Trie[] children;
  3. private boolean isEnd;
  4. public Trie() {
  5. children = new Trie[26];
  6. isEnd = false;
  7. }
  8. public void insert(String word) {
  9. Trie node = this;
  10. for (int i = 0; i < word.length(); i++) {
  11. char ch = word.charAt(i);
  12. int index = ch - 'a';
  13. if (node.children[index] == null) {
  14. node.children[index] = new Trie();
  15. }
  16. node = node.children[index];
  17. }
  18. node.isEnd = true;
  19. }
  20. public boolean search(String word) {
  21. Trie node = searchPrefix(word);
  22. return node != null && node.isEnd;
  23. }
  24. public boolean startsWith(String prefix) {
  25. return searchPrefix(prefix) != null;
  26. }
  27. private Trie searchPrefix(String prefix) {
  28. Trie node = this;
  29. for (int i = 0; i < prefix.length(); i++) {
  30. char ch = prefix.charAt(i);
  31. int index = ch - 'a';
  32. if (node.children[index] == null) {
  33. return null;
  34. }
  35. node = node.children[index];
  36. }
  37. return node;
  38. }
  39. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/788788
推荐阅读
相关标签
  

闽ICP备14008679号