File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // trie
2
+ // trie implementation adopt from: https://walkccc.me/LeetCode/problems/3042/
3
+
4
+ struct TrieNode {
5
+ unordered_map<char , shared_ptr<TrieNode>> c;
6
+ int cnt = 0 ;
7
+ };
8
+
9
+ class Trie {
10
+ public:
11
+ void insert (const string &w) {
12
+ int cnt = 0 ;
13
+ shared_ptr<TrieNode> n = root;
14
+ for (char j : w) {
15
+ if (!n->c [j])
16
+ n->c [j] = make_shared<TrieNode>();
17
+ n = n->c [j];
18
+ n->cnt ++;
19
+ }
20
+ }
21
+
22
+ int search (const string &w) {
23
+ shared_ptr<TrieNode> n = root;
24
+ if (!n->c [w[0 ]])
25
+ return 0 ;
26
+ n = n->c [w[0 ]];
27
+ int ans = n->cnt ;
28
+ for (int i = 1 ; i < w.size (); i++) {
29
+ if (!n->c [w[i]])
30
+ return 0 ;
31
+ n = n->c [w[i]];
32
+ ans = min (ans, n->cnt );
33
+ }
34
+ return ans;
35
+ }
36
+
37
+ private:
38
+ shared_ptr<TrieNode> root = make_shared<TrieNode>();
39
+ };
40
+
41
+ class Solution {
42
+ public:
43
+ int prefixCount (vector<string>& words, string pref) {
44
+ Trie trie;
45
+
46
+ for (string w : words)
47
+ trie.insert (w);
48
+
49
+ return trie.search (pref);
50
+ }
51
+ };
You can’t perform that action at this time.
0 commit comments