Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
李楚霏
/
leetCode_Solution_Record
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
f0551119
authored
Oct 08, 2020
by
李楚霏
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
week7-work1
parent
855cb035
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
61 additions
and
0 deletions
+61
-0
70works/week7/work/day46_208_implement-trie-prefix-tree.cpp
+61
-0
No files found.
70works/week7/work/day46_208_implement-trie-prefix-tree.cpp
0 → 100644
View file @
f0551119
class
Trie
{
struct
TrieNode
{
map
<
char
,
TrieNode
*>
child_table
;
int
end
;
TrieNode
()
:
end
(
0
)
{};
};
public
:
/** Initialize your data structure here. */
Trie
()
{
root
=
new
TrieNode
();
}
/** Inserts a word into the trie. */
void
insert
(
string
word
)
{
TrieNode
*
cur
=
root
;
for
(
int
i
=
0
;
i
<
word
.
size
();
i
++
)
{
if
(
cur
->
child_table
.
count
(
word
[
i
])
==
0
)
{
cur
->
child_table
[
word
[
i
]]
=
new
TrieNode
();
}
cur
=
cur
->
child_table
[
word
[
i
]];
}
cur
->
end
=
1
;
}
/** Returns if the word is in the trie. */
bool
search
(
string
word
)
{
return
find
(
word
,
1
);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool
startsWith
(
string
prefix
)
{
return
find
(
prefix
,
0
);
}
private
:
TrieNode
*
root
;
bool
find
(
string
prefix
,
int
exact_match
)
{
TrieNode
*
cur
=
root
;
for
(
int
i
=
0
;
i
<
prefix
.
size
();
i
++
)
{
if
(
cur
->
child_table
.
count
(
prefix
[
i
])
==
0
)
{
return
false
;
}
cur
=
cur
->
child_table
[
prefix
[
i
]];
}
if
(
exact_match
)
{
return
cur
->
end
?
true
:
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);
*/
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment