您的位置:首页 > 其它

Add and Search Word - Data Structure Design

2015-08-18 23:02 281 查看
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
.

Analyse: The same as Implement Trie. If '.' is encountered, we need to traversal all situations.

Runtime: 88ms.

class TrieNode{
public:
TrieNode* childNode[27];
bool isVal;
TrieNode(){
isVal = false;
for(int i = 0; i < 27; i++)
childNode[i] = NULL;
}
};
class WordDictionary {
private:
TrieNode* root;
public:
WordDictionary(){
root = new TrieNode();
}
// Adds a word into the data structure.
void addWord(string word) {
TrieNode* temp = root;
for(int i = 0; i < word.size(); i++){
int index = word[i] - 'a';
if(word[i] == '.')
index = 26;
else{
if(temp->childNode[index] == NULL)
temp->childNode[index] = new TrieNode();
}
temp = temp->childNode[index];
}
temp->isVal = true; //word has been inserted
}

// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return levelSearch(word, root, 0);
}

bool levelSearch(string& word, TrieNode* root, int index){
TrieNode* temp = root;
if(!temp) return false; //length of the word is larger than that of the strings in the trie
if(index >= word.size()) return temp->isVal;

if(word[index] != '.')
return levelSearch(word, temp->childNode[word[index] - 'a'], index + 1);
else{
for(int i = 0; i < 26; i++)
if(levelSearch(word, temp->childNode[i], index + 1)) return true;
return false;
}
}
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: