-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path208.implement-trie-prefix-tree.cpp
More file actions
81 lines (74 loc) · 1.8 KB
/
Copy path208.implement-trie-prefix-tree.cpp
File metadata and controls
81 lines (74 loc) · 1.8 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
71
72
73
74
75
76
77
78
79
80
/*
* @lc app=leetcode id=208 lang=cpp
*
* [208] Implement Trie (Prefix Tree)
*/
// @lc code=start
#include "bits/stdc++.h"
using namespace std;
class Trie {
public:
struct Node
{
char val_;
bool isLast_ = false;
vector<Node*> children_;
Node(char val) : val_(val), children_(26, nullptr) {}
};
Node *root = new Node('\0');
Trie() {
}
void insert(string word) {
Node *node = root;
for (int i = 0; i < word.size(); ++i)
{
auto ch = word[i];
// if the current character is not in the children, create a new node
if (!node->children_[ch - 'a'])
{
node->children_[ch - 'a'] = new Node(ch);
}
node = node->children_[ch - 'a'];
if (i == word.size() - 1) {
node->isLast_ = true;
}
}
}
bool search(string word) {
Node *node = root;
for (char ch : word) {
if (node->children_[ch - 'a'])
{
node = node->children_[ch - 'a'];
}
else
{
return false;
}
}
if (node->isLast_) return true;
return false;
}
bool startsWith(string prefix) {
Node *node = root;
for (char ch : prefix) {
if (node->children_[ch - 'a'])
{
node = node->children_[ch - 'a'];
}
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);
*/
// @lc code=end