-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leetcode0208.cpp
64 lines (57 loc) · 1.53 KB
/
Leetcode0208.cpp
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
#include <bits/stdc++.h>
using namespace std;
//Filename: Leetcode0208.cpp
//
//Author: dezhonger - csdisassembly@gmail.com
//Create: 2021-05-13 00:03:29
//Last modified: 2021-05-13 00:12:26
const int N = 2000010;
int son[N][26], idx;
bool w[N];
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
idx = 0;
memset(son, 0, sizeof son);
memset(w, 0, sizeof w);
}
/** Inserts a word into the trie. */
void insert(string word) {
int n = word.size(), p = 0;
for (int i = 0; i < n; i++) {
int c = word[i] - 'a';
if (!son[p][c]) son[p][c] = ++idx;
p = son[p][c];
}
w[p] = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
int n = word.size(), p = 0;
for (int i = 0; i < n; i++) {
int c = word[i] - 'a';
if (!son[p][c]) return false;
p = son[p][c];
}
return w[p];
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int n = prefix.size(), p = 0;
for (int i = 0; i < n; i++) {
int c = prefix[i] - 'a';
if (!son[p][c]) return false;
p = son[p][c];
}
return true;
}
};
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif
ios::sync_with_stdio (false);
cin.tie (0);
return 0;
}