leetcode Add and Search Word - Data structure design

柔情只为你懂 2022-08-05 01:30 236阅读 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
Note:
You may assume that all words are consist of lowercase letters a-z.
题目来源:https://leetcode.com/problems/add-and-search-word-data-structure-design/

分析

关于字典树(trie tree)的概念和分析见:http://blog.csdn.net/u010902721/article/details/45749447
主要挑战性在于’.’的匹配。遇到一个’.’就得匹配当前next[]数组里面所有的有效分支。用个递归函数,递归匹配吧。

代码

  1. class TrieNode{
  2. public:
  3. int flag;
  4. TrieNode* next[26];
  5. TrieNode(){
  6. flag = 0;
  7. for(int i = 0; i < 26; i++){
  8. next[i] = NULL;
  9. }
  10. }
  11. };
  12. class WordDictionary {
  13. private:
  14. TrieNode *root;
  15. public:
  16. WordDictionary(){
  17. root = new TrieNode();
  18. }
  19. // Adds a word into the data structure.
  20. void addWord(string word) {
  21. TrieNode* p = root;
  22. int len = word.length();
  23. if(len <= 0)
  24. return;
  25. for(int i = 0; i < len; i++){
  26. int d = word.at(i) - 'a';
  27. if((p->next)[d] == NULL){
  28. p->next[d] = new TrieNode();
  29. p->next[d]->flag = 0;
  30. }
  31. p = p->next[d];
  32. }
  33. p->flag = 1;
  34. }
  35. // Returns if the word is in the data structure. A word could
  36. // contain the dot character '.' to represent any one letter.
  37. bool searchHelp(string word, struct TrieNode *root){
  38. struct TrieNode *p = root;
  39. int len = word.length();
  40. if(len <= 0){
  41. //为了匹配字符串中字符'.'是最后一个字符的情形。
  42. if(p->flag == 1)
  43. return true;
  44. else
  45. return false;
  46. }
  47. if(root == NULL)
  48. return false;
  49. for(int i = 0; i < len; i++){
  50. if(word.at(i) == '.'){
  51. bool result = false;
  52. for(int j = 0; j < 26; j++){
  53. if(p->next[j] != NULL){
  54. result = result || searchHelp(word.substr(i+1), p->next[j]);
  55. }
  56. }
  57. return result;
  58. }
  59. else
  60. {
  61. int d = word.at(i) - 'a';
  62. if(p->next[d] == NULL)
  63. return false;
  64. p = p->next[d];
  65. }
  66. }
  67. if(p->flag == 1)
  68. return true;
  69. else
  70. return false;
  71. }
  72. bool search(string word) {
  73. int len = word.length();
  74. if(len <= 0)
  75. return true;
  76. return searchHelp(word, root);
  77. }
  78. };
  79. // Your WordDictionary object will be instantiated and called as such:
  80. // WordDictionary wordDictionary;
  81. // wordDictionary.addWord("word");
  82. // wordDictionary.search("pattern");

发表评论

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

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

相关阅读