211. 添加与搜索单词 - 数据结构设计

  1. class WordDictionary {
  2. class TrieNode {
  3. public TrieNode[] children;
  4. public boolean isEnd = false;
  5. public TrieNode() {
  6. children = new TrieNode[26];
  7. isEnd = false;
  8. }
  9. }
  10. TrieNode root;
  11. /** Initialize your data structure here. */
  12. public WordDictionary() {
  13. root = new TrieNode();
  14. }
  15. public void addWord(String word) {
  16. if (word == null || word.length() == 0)
  17. return ;
  18. TrieNode node = root;
  19. char[] chs = word.toCharArray();
  20. for (char ch : chs) {
  21. if (node.children[ch - 'a'] == null)
  22. node.children[ch - 'a'] = new TrieNode();
  23. node = node.children[ch - 'a'];
  24. }
  25. node.isEnd = true;
  26. }
  27. public boolean search(String word) {
  28. return dfs(word, root, 0);
  29. }
  30. private boolean dfs(String word, TrieNode node, int start) {
  31. if (start == word.length())
  32. return node.isEnd;
  33. char ch = word.charAt(start);
  34. if (ch != '.') {
  35. if (node.children[ch - 'a'] == null)
  36. return false;
  37. return dfs(word, node.children[ch - 'a'], start + 1);
  38. } else {
  39. int index = 0;
  40. for (index = 0; index < 26; index++) {
  41. // 递归遍历node节点后面的所有路径
  42. if (node.children[index] != null && dfs(word, node.children[index], start + 1))
  43. return true;
  44. }
  45. return false;
  46. }
  47. }
  48. }
  49. /**
  50. * Your WordDictionary object will be instantiated and called as such:
  51. * WordDictionary obj = new WordDictionary();
  52. * obj.addWord(word);
  53. * boolean param_2 = obj.search(word);
  54. */