您的位置:首页 > Web前端 > JavaScript

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

2015-07-12 20:45 716 查看

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/

字典树,在上一题的基础上稍做修改。/article/7170972.html

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

/**
* @constructor
*/
var WordDictionary = function() {
this.root = new TrieNode('root');
};

function TrieNode(key) {
return {
key : key,
isWord : false
};
}

/**
* @param {string} word
* @return {void}
* Adds a word into the data structure.
*/
WordDictionary.prototype.addWord = function(word) {
var tree = this.root, i, curr;
for(i = 0; i < word.length; i++){
curr = word[i];
if(!tree[curr]){
tree[curr] = new TrieNode(curr);
}
tree = tree[curr];
}
tree.isWord = true;
};

/**
* @param {string} word
* @return {boolean}
* Returns if the word is in the data structure. A word could
* contain the dot character '.' to represent any one letter.
*/
WordDictionary.prototype.search = function(word) {
return searchWord(word, this.root);

function searchWord(word, tree){
if(word === "" && tree.isWord){
return true;
}
if(word[0] !== '.'){
if(!tree[word[0]]){
return false;
}else{
return searchWord(word.substring(1, word.length), tree[word[0]]);
}
}else{
for(var i in tree){
if(i === 'key' || i === 'isWord'){
continue;
}
if(searchWord(word.substring(1, word.length), tree[i])){
return true;
}
}
return false;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: