|
| 1 | +#include <bits/stdc++.h> |
| 2 | +#define ll long long |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +struct trie_node { |
| 6 | + ll word_count; |
| 7 | + ll prefix_count; |
| 8 | + trie_node* edges[26]; |
| 9 | + |
| 10 | + trie_node() { |
| 11 | + this->word_count = 0; |
| 12 | + this->prefix_count = 0; |
| 13 | + for(int i = 0; i < 26; i++) { |
| 14 | + this->edges[i] = NULL; |
| 15 | + } |
| 16 | + } |
| 17 | +}; |
| 18 | + |
| 19 | +void add_word(trie_node* &root, string &str, int index) { |
| 20 | + if (index == str.length()) { |
| 21 | + root->word_count += 1; |
| 22 | + return; |
| 23 | + } |
| 24 | + root->prefix_count += 1; |
| 25 | + int i = int(str[index] - 'a'); |
| 26 | + if (root->edges[i] == NULL) { |
| 27 | + root->edges[i] = new trie_node(); |
| 28 | + } |
| 29 | + add_word(root->edges[i], str, index+1); |
| 30 | +} |
| 31 | + |
| 32 | +ll count_prefix(trie_node* root, string &prefix, int index) { |
| 33 | + if (index == prefix.length()) { |
| 34 | + return root->prefix_count; |
| 35 | + } |
| 36 | + int i = int(prefix[index] - 'a'); |
| 37 | + if (root->edges[i] == NULL) { |
| 38 | + return 0; |
| 39 | + } |
| 40 | + return count_prefix(root->edges[i], prefix, index+1); |
| 41 | +} |
| 42 | + |
| 43 | +int main() { |
| 44 | + trie_node* root = new trie_node(); |
| 45 | + string s = "codechef"; |
| 46 | + add_word(root, s, 0); |
| 47 | + s = "codeforces"; |
| 48 | + add_word(root, s, 0); |
| 49 | + s = "youtube"; |
| 50 | + add_word(root, s, 0); |
| 51 | + s = "google"; |
| 52 | + add_word(root, s, 0); |
| 53 | + s = "code"; |
| 54 | + cout<<count_prefix(root, s, 0)<<endl; |
| 55 | + return 0; |
| 56 | +} |
0 commit comments