?LeetCode刷題實(shí)戰(zhàn)211:添加與搜索單詞
Design a data structure that supports adding new words and finding if a string matches any previously added string.
題意
WordDictionary() 初始化詞典對(duì)象
void addWord(word) 將 word 添加到數(shù)據(jù)結(jié)構(gòu)中,之后可以對(duì)它進(jìn)行匹配
bool search(word) 如果數(shù)據(jù)結(jié)構(gòu)中存在字符串與 word 匹配,則返回 true ;否則,返回 false 。word 中可能包含一些 '.' ,每個(gè) . 都可以表示任何一個(gè)字母。
示例
輸入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
輸出:
[null,null,null,null,false,true,true,true]
解釋?zhuān)?br mpa-from-tpl="t">WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True
提示:
1 <= word.length <= 500
addWord 中的 word 由小寫(xiě)英文字母組成
search 中的 word 由 '.' 或小寫(xiě)英文字母組成
最多調(diào)用 50000 次 addWord 和 search
解題
class WordDictionary {
public:
//定義字典樹(shù)中每個(gè)節(jié)點(diǎn)的結(jié)構(gòu)
struct Node{
bool isword = false; //用于標(biāo)記當(dāng)前節(jié)點(diǎn)是否為單詞的最后一個(gè)字符
Node* next[27] = {};
};
Node* root; //每一個(gè)class都有一棵字典樹(shù)
/** Initialize your data structure here. */
WordDictionary() {
root = new Node(); //新建一棵字典樹(shù)
}
/** Adds a word into the data structure. */
void addWord(string word) {
Node* tmp = root;
for(auto w: word){
if(tmp->next[w - 'a'] == NULL){ //還沒(méi)有這個(gè)節(jié)點(diǎn)
Node* tt = new Node();
tmp->next[w - 'a'] = tt; //那就新建節(jié)點(diǎn)
}
tmp = tmp->next[w - 'a'];
}
tmp->isword = true; //遍歷完一個(gè)單詞
}
/** 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 dfs(word, root, 0);
}
bool dfs(string word, Node* root, int i){
if(!root) return false;
if(i >= word.size()) return root->isword; //看看是不是一個(gè)完整的單詞
if(word[i] != '.'){
if(root->next[word[i] - 'a']){
return dfs(word, root->next[word[i] - 'a'], i+1);
}
else return false;
}
for(auto t: root->next){
if(t){
if(dfs(word, t, i+1)) return true;
}
}
return false;
}
};
LeetCode1-200題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)201:數(shù)字范圍按位與
LeetCode刷題實(shí)戰(zhàn)202:快樂(lè)數(shù)
LeetCode刷題實(shí)戰(zhàn)203:移除鏈表元素
LeetCode刷題實(shí)戰(zhàn)204:計(jì)數(shù)質(zhì)數(shù)
LeetCode刷題實(shí)戰(zhàn)205:同構(gòu)字符串
LeetCode刷題實(shí)戰(zhàn)206:反轉(zhuǎn)鏈表
LeetCode刷題實(shí)戰(zhàn)207:課程表
LeetCode刷題實(shí)戰(zhàn)208:實(shí)現(xiàn) Trie (前綴樹(shù))
LeetCode刷題實(shí)戰(zhàn)209:長(zhǎng)度最小的子數(shù)組
LeetCode刷題實(shí)戰(zhàn)210:課程表 II
