您的位置:首页 > 其它

[leetcode] Add and Search Word - Data structure design

2015-06-13 16:15 549 查看
From : https://leetcode.com/problems/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


class WordDictionary {
public:
struct TrieNode {
TrieNode *child[26];
bool isWord;
TrieNode() : isWord(false) {
for(auto &a : child) a = NULL;
}
};

WordDictionary() {
root = new TrieNode();
}

// Adds a word into the data structure.
void addWord(string word) {
TrieNode *p = root;
for(auto &w : word) {
if(!p->child[w-'a']) p->child[w-'a'] = new TrieNode();
p = p->child[w-'a'];
}
p->isWord = true;
}

// 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 searchCore(word, root, 0);
}

bool searchCore(string &word, TrieNode* pre, int index) {
if(index == word.size()) return pre->isWord;
if(word[index] == '.') {
for(auto &cur : pre->child) if(cur && searchCore(word, cur, index+1)) return true;
return false;
} else {
TrieNode* cur = pre->child[word[index]-'a'];
return cur && searchCore(word, cur, index+1);
}
}
private:
TrieNode *root;
};

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