/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
node* p = root;
for (int i = 0; i < prefix.size(); ++i) {
int x = prefix[i] - 'a';
if (p->next[x] != nullptr) {
p = p->next[x];
} else {
return false;
}
}
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);
*/
字典树还和dfs结合构造新的题目如leetcode 211. 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.
1
2
3
4
5
6
7
8
9
10
11
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.
思路:字典树+dfs时间复杂度 查询的时候复杂度O(26^n) n为‘.’的个数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class WordDictionary {
public:
/** Initialize your data structure here. */
WordDictionary() {
}
class node {
public:
node* next[26];
int end;
node() {
for (int i = 0; i < 26; ++i) {
next[i] = nullptr;
}
end = 0;
}
};
class Trie {
public:
node* root;
Trie() {
root = new node();
}
void add(string s) {
if (s.size() == 0) return ;
node* p = root;
for (int i = 0; i < s.size(); ++i) {
int x = s[i] - 'a';
if (p->next[x] == nullptr) {
p->next[x] = new node();
p = p->next[x];
} else {
p = p->next[x];
}
}
p->end = 1;
}
bool search(string& s, int pos, node *p) {
if (s.size() == pos && p->end == 1) {
return true;
}
if (s[pos] == '.') {
for (int j = 0; j < 26; ++j) {
if (p->next[j] != nullptr) {
if (search(s, pos + 1, p->next[j])) return true;
}
}
} else {
int x = (int)(s[pos] - 'a');
if (x >= 0 && x < 26 && p->next[x] != nullptr && search(s, pos + 1, p->next[x])) return true;
}
return false;
}
};
/** Adds a word into the data structure. */
void addWord(string word) {
ac.add(word);
}
/** 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) {
if (ac.search(word, 0, ac.root)) return true;
return false;
}
private:
Trie ac;
};
/**
* Your WordDictionary object will be instantiated and called as such: