#define cti(x) (x-'a')
#define itc(x) (x+'a')
const int maxn = 100005;
const int sigma_size = 26;
class Trie {
public:
/** Initialize your data structure here. */
int ch[maxn][sigma_size], val[maxn]={}, sz;
Trie() { sz = 1, memset(ch[0], 0, sizeof(ch[0])); }
/** Inserts a word into the trie. */
void insert(string word) {
int o = 0;
for (int i = 0; i < word.size(); ++i) {
if (!ch[o][cti(word[i])])
memset(ch[sz], 0, sizeof(ch[sz])), val[sz] = 0, ch[o][cti(word[i])] = sz++;
o = ch[o][cti(word[i])];
}
val[o] = 1;
}
/** Returns if the word is in the trie. */
bool search(string word) {
int o=0;
for (int i = 0; i < word.size(); ++i){
if (!ch[o][cti(word[i])]) return false;
o = ch[o][cti(word[i])];
}
return val[o]==1;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int o=0;
for (int i = 0; i < prefix.size(); ++i){
if (!ch[o][cti(prefix[i])]) return false;
o = ch[o][cti(prefix[i])];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* bool param_2 = obj.search(word);
* bool param_3 = obj.startsWith(prefix);
*/
Leetcode 208. 实现 Trie (前缀树)
猜你喜欢
转载自blog.csdn.net/bendaai/article/details/81151810
今日推荐
周排行