Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
anqiwa
myLeetcodeSolu
Commits
c1d0e5a8
Commit
c1d0e5a8
authored
Dec 04, 2021
by
anqiwa
😲
Browse files
add trie section
parent
50f8558e
Changes
2
Hide whitespace changes
Inline
Side-by-side
Trie/1032. stream of char/1032.stream-of-characters.cpp
0 → 100644
View file @
c1d0e5a8
/*
* @lc app=leetcode id=1032 lang=cpp
*
* [1032] Stream of Characters
*/
// @lc code=start
class
StreamChecker
{
// 此题对ood也是很好的考察
struct
TrieNode
{
bool
isEnd
;
TrieNode
*
next
[
26
];
//constructor
TrieNode
()
{
isEnd
=
false
;
for
(
int
i
=
0
;
i
<
26
;
++
i
)
{
next
[
i
]
=
nullptr
;
}
}
};
TrieNode
*
root
;
string
curr
;
public:
StreamChecker
(
vector
<
string
>
&
words
)
{
// construct the trie
root
=
new
TrieNode
();
for
(
auto
&
str
:
words
)
{
addWord
(
str
);
}
}
bool
query
(
char
letter
)
{
curr
.
push_back
(
letter
);
return
find
();
}
void
addWord
(
string
&
str
)
{
// add word from the back to the front
TrieNode
*
ptr
=
root
;
for
(
int
i
=
str
.
size
()
-
1
;
i
>=
0
;
--
i
)
{
char
ch
=
str
[
i
];
if
(
ptr
->
next
[
ch
-
'a'
]
==
nullptr
)
{
ptr
->
next
[
ch
-
'a'
]
=
new
TrieNode
();
}
ptr
=
ptr
->
next
[
ch
-
'a'
];
}
ptr
->
isEnd
=
true
;
}
// find from back to front if curr is in the trie
bool
find
()
{
TrieNode
*
ptr
=
root
;
int
i
=
curr
.
size
()
-
1
;
while
(
i
>=
0
)
{
char
ch
=
curr
[
i
];
if
(
ptr
->
next
[
ch
-
'a'
])
{
ptr
=
ptr
->
next
[
ch
-
'a'
];
if
(
ptr
->
isEnd
)
{
return
true
;
}
--
i
;
}
else
break
;
}
return
false
;
}
};
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
/**
* Your StreamChecker object will be instantiated and called as such:
* StreamChecker* obj = new StreamChecker(words);
* bool param_1 = obj->query(letter);
*/
// @lc code=end
Trie/1032. stream of char/Readme.md
0 → 100644
View file @
c1d0e5a8
# 1032. Stream of char
前缀树的题目的代码量很大,但是思路很好想,所以熟练度很重要
### 核心思想:
每次query一个char,从那个字符开始往前看,所以建树时也要从后往前:
```
cpp
void
addWord
(
string
&
str
)
{
// add word from the back to the front
TrieNode
*
ptr
=
root
;
for
(
int
i
=
str
.
size
()
-
1
;
i
>=
0
;
--
i
)
{
char
ch
=
str
[
i
];
if
(
ptr
->
next
[
ch
-
'a'
]
==
nullptr
)
{
ptr
->
next
[
ch
-
'a'
]
=
new
TrieNode
();
}
ptr
=
ptr
->
next
[
ch
-
'a'
];
}
ptr
->
isEnd
=
true
;
}
```
此题其他部分就走流程,先要implement一个trieNode,在把string放入即可:
```
cpp
struct
TrieNode
{
bool
isEnd
;
TrieNode
*
next
[
26
];
//constructor
TrieNode
()
{
isEnd
=
false
;
for
(
int
i
=
0
;
i
<
26
;
++
i
)
{
next
[
i
]
=
nullptr
;
}
}
};
```
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