-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path208.cpp
More file actions
70 lines (60 loc) · 1.56 KB
/
208.cpp
File metadata and controls
70 lines (60 loc) · 1.56 KB
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
//
// 208.cpp
// LeetCode
//
// Created by 张佐玮 on 15/8/7.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Implement Trie (Prefix Tree)
//
#include <iostream>
using namespace std;
class TrieNode {
public:
bool end;
TrieNode *child[26];
// Initialize your data structure here.
TrieNode() {
for (int i = 0; i < 26; i++) {
child[i] = NULL;
}
end = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *current = root;
for (auto ch: word) {
if (current -> child[ch-'a'] == NULL) {
TrieNode *temp = new TrieNode();
current -> child[ch-'a'] = temp;
}
current = current -> child[ch-'a'];
}
current -> end = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *current = root;
for (int i = 0; i < word.size() && current != NULL; i++) {
current = current -> child[word[i]-'a'];
}
return current != NULL && current -> end;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *current = root;
for (int i = 0; i < prefix.size() && current != NULL; i++) {
current = current -> child[prefix[i]-'a'];
}
return current != NULL;
}
private:
TrieNode* root;
};