[LeetCode][JavaScript]Add and Search Word - Data structure design

Add and Search Word - Data structure design

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/

 

 

 


 

 

字典树,在上一题的基础上稍做修改。http://www.cnblogs.com/Liok3187/p/4626730.html

遇到'.'就要采用递归的方式,遍历这一层词典里所有的词。

 1 /**
 2  * @constructor
 3  */
 4 var WordDictionary = function() {
 5     this.root = new TrieNode('root');
 6 };
 7 
 8 function TrieNode(key) {
 9     return {
10         key : key,  
11         isWord : false
12     };
13 }
14 
15 /**
16  * @param {string} word
17  * @return {void}
18  * Adds a word into the data structure.
19  */
20 WordDictionary.prototype.addWord = function(word) {
21     var tree = this.root, i, curr;
22     for(i = 0; i < word.length; i++){
23         curr = word[i];
24         if(!tree[curr]){
25             tree[curr] = new TrieNode(curr);
26         }
27         tree = tree[curr];
28     }
29     tree.isWord = true;
30 };
31 
32 /**
33  * @param {string} word
34  * @return {boolean}
35  * Returns if the word is in the data structure. A word could
36  * contain the dot character '.' to represent any one letter.
37  */
38 WordDictionary.prototype.search = function(word) {
39     return searchWord(word, this.root);
40 
41     function searchWord(word, tree){
42         if(word === "" && tree.isWord){
43             return true;
44         }
45         if(word[0] !== '.'){
46             if(!tree[word[0]]){
47                 return false;
48             }else{
49                 return searchWord(word.substring(1, word.length), tree[word[0]]);
50             }
51         }else{
52             for(var i in tree){
53                 if(i === 'key' || i === 'isWord'){
54                     continue;
55                 }
56                 if(searchWord(word.substring(1, word.length), tree[i])){
57                     return true;
58                 }
59             }
60             return false;
61         }
62     }
63 };

 

posted @ 2015-07-12 20:45  `Liok  阅读(470)  评论(0编辑  收藏  举报