leetcode 链接:https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/

题目

image.png
image.png

解法

  1. public class WordDictionary {
  2. private class Node {
  3. private static final int size = 26;
  4. // 当前节点是否为某个单词的末位
  5. boolean isWord;
  6. // 指向子节点
  7. Node[] next;
  8. public Node(boolean isWord) {
  9. this.isWord = isWord;
  10. next = new Node[size];
  11. }
  12. public Node() {
  13. this(false);
  14. }
  15. public boolean containsKey(char ch) {
  16. return next[ch - 'a'] != null;
  17. }
  18. public Node get(char ch) {
  19. return next[ch - 'a'];
  20. }
  21. public void put(char ch, Node node) {
  22. next[ch - 'a'] = node;
  23. }
  24. }
  25. // 根节点
  26. private final Node root;
  27. /**
  28. * Initialize your data structure here.
  29. */
  30. public WordDictionary() {
  31. this.root = new Node();
  32. }
  33. /**
  34. * Adds a word into the data structure.
  35. */
  36. public void addWord(String word) {
  37. Node curr = root;
  38. for (int i = 0; i < word.length(); i++) {
  39. char ch = word.charAt(i);
  40. if (!curr.containsKey(ch)) {
  41. curr.put(ch, new Node());
  42. }
  43. curr = curr.get(ch);
  44. }
  45. curr.isWord = true;
  46. }
  47. /**
  48. * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
  49. */
  50. public boolean search(String word) {
  51. return search(root, word, 0);
  52. }
  53. private boolean search(Node curr, String word, int index) {
  54. if (word.length() == index) {
  55. // 到达末尾
  56. return curr.isWord;
  57. }
  58. char ch = word.charAt(index);
  59. if (ch == '.') {
  60. // 遍历所有的节点一一匹配,如果能够终止于true,说明能够匹配成功
  61. for (Node node : curr.next) {
  62. if (node != null && search(node, word, index + 1)) {
  63. return true;
  64. }
  65. }
  66. return false;
  67. } else if (!curr.containsKey(ch)) {
  68. return false;
  69. } else {
  70. return search(curr.get(ch), word, index + 1);
  71. }
  72. }
  73. }