211. Add and Search Word - Data structure design

布满荆棘的人生 2022-04-24 16:56 231阅读 0赞
  1. Design a data structure that supports the following two operations:
  2. void addWord(word)
  3. bool search(word)
  4. 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.
  5. Example:
  6. addWord("bad")
  7. addWord("dad")
  8. addWord("mad")
  9. search("pad") -> false
  10. search("bad") -> true
  11. search(".ad") -> true
  12. search("b..") -> true
  13. Note:
  14. You may assume that all words are consist of lowercase letters a-z.

本题与208. Implement Trie (Prefix Tree)类似,都是前缀树的应用。详细代码如下:

  1. /**
  2. * 208. Implement Trie (Prefix Tree)
  3. * 前缀树的节点定义
  4. */
  5. class TrieNode {
  6. private TrieNode[] links;//最多有26个子节点
  7. private final int MAX_NODE = 26;
  8. private boolean isEnd;//判断该节点是否是尾结点(即是否存在从根节点到该节点的单词)
  9. public TrieNode() {
  10. links = new TrieNode[MAX_NODE];
  11. }
  12. public boolean containsKey(char ch) {
  13. return links[ch-'a'] != null;
  14. }
  15. public TrieNode get(char ch) {
  16. return links[ch-'a'];
  17. }
  18. public void put(char ch, TrieNode node) {
  19. links[ch-'a'] = node;
  20. }
  21. public boolean isEnd() {
  22. return isEnd;
  23. }
  24. public void setEnd(boolean end) {
  25. isEnd = end;
  26. }
  27. }
  28. /**
  29. * Your WordDictionary object will be instantiated and called as such:
  30. * WordDictionary obj = new WordDictionary();
  31. * obj.addWord(word);
  32. * boolean param_2 = obj.search(word);
  33. */
  34. class WordDictionary {
  35. private TrieNode root;
  36. /** Initialize your data structure here. */
  37. public WordDictionary() {
  38. root = new TrieNode();
  39. }
  40. /** Adds a word into the data structure. */
  41. public void addWord(String word) {
  42. TrieNode node = root;
  43. for(int i = 0; i < word.length(); ++i) {
  44. char ch = word.charAt(i);
  45. if(!node.containsKey(ch)) {
  46. node.put(ch, new TrieNode());
  47. }
  48. node = node.get(ch);
  49. }
  50. node.setEnd(true);
  51. }
  52. /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
  53. public boolean search(String word) {
  54. return searchFrom(word, root);
  55. }
  56. private boolean searchFrom(String word, TrieNode node) {
  57. if(node == null || word == null) return false;
  58. for(int i = 0; i < word.length(); ++i) {
  59. char ch = word.charAt(i);
  60. if(ch != '.') {
  61. if(!node.containsKey(ch)) {
  62. return false;
  63. }
  64. node = node.get(ch);
  65. } else {
  66. String sub = word.substring(i+1);
  67. for(char cc = 'a'; cc <= 'z'; ++cc) {
  68. if(searchFrom(sub, node.get(cc)))
  69. return true;
  70. }
  71. return false;
  72. }
  73. }
  74. return node != null && node.isEnd();
  75. }
  76. }

发表评论

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

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

相关阅读