leetcode 211. Add and Search Word - Data structure design 字典树的简单应用

痛定思痛。 2022-06-08 09:24 275阅读 0赞

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

addWord(“bad”)
addWord(“dad”)
addWord(“mad”)
search(“pad”) -> false
search(“bad”) -> true
search(“.ad”) -> true
search(“b..”) -> true

这道题和leetcode 208. Implement Trie (Prefix Tree) 字典树的构造 基本一样,不过在搜索的过程中使用了DFS深度优先遍历,字典树应该记住。

代码如下:

  1. public class WordDictionary
  2. {
  3. private TrieNode root = new TrieNode();
  4. public void addWord(String word)
  5. {
  6. Map<Character, TrieNode> children = root.children;
  7. for(int i=0; i<word.length(); i++)
  8. {
  9. char c = word.charAt(i);
  10. TrieNode t=null;
  11. if(children.containsKey(c))
  12. t = children.get(c);
  13. else
  14. {
  15. t = new TrieNode(c);
  16. children.put(c, t);
  17. }
  18. children = t.children;
  19. if(i==word.length()-1)
  20. t.leaf=true;
  21. }
  22. }
  23. public boolean search(String word)
  24. {
  25. return searchNode(word, root);
  26. }
  27. /*
  28. * 递归搜索
  29. *
  30. * */
  31. public boolean searchNode(String word, TrieNode tn)
  32. {
  33. if(tn==null)
  34. return false;
  35. if(word.length() == 0 )
  36. return tn.leaf;
  37. Map<Character, TrieNode> children = tn.children;
  38. TrieNode t = null;
  39. char c = word.charAt(0);
  40. if(c=='.')
  41. {
  42. for(char key : children.keySet() )
  43. {
  44. if(searchNode(word.substring(1), children.get(key) ))
  45. return true;
  46. }
  47. return false;
  48. } else if(!children.containsKey(c))
  49. return false;
  50. else
  51. {
  52. t = children.get(c);
  53. return searchNode(word.substring(1), t);
  54. }
  55. }
  56. }
  57. class TrieNode
  58. {
  59. // Initialize your data structure here.
  60. char c;
  61. boolean leaf;
  62. HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
  63. public TrieNode(char c)
  64. {
  65. this.c = c;
  66. }
  67. public TrieNode(){};
  68. }

发表评论

表情:
评论列表 (有 0 条评论,275人围观)

还没有评论,来说两句吧...

相关阅读