codekofi
← All problems

Problem 115

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1struct Trie {
2 Trie* kids[26] = {};
3 bool word = false;
4};
5
6void add(Trie* node, const string& text) {
7
8 for (char c : text) {
9
10 int i = c - 'a';
11
12 if (!node->kids[i]) {
13 node->kids[i] = new Trie();
14 }
15
16 node = node->kids[i];
17 }
18
19 node->word = true;
20}
21
22bool hunt(Trie* node, const string& pattern, int i) {
23
24 if (!node) {
25 return false;
26 }
27
28 int n = pattern.size();
29
30 if (i == n) {
31 return node->word;
32 }
33
34 char c = pattern[i];
35
36 if (c != '.') {
37 return hunt(node->kids[c - 'a'], pattern, i + 1);
38 }
39
40 for (int k = 0; k < 26; k++) {
41
42 if (hunt(node->kids[k], pattern, i + 1)) {
43 return true;
44 }
45 }
46
47 return false;
48}
49
50vector<string> solution(const vector<string>& ops,
51 const vector<string>& args) {
52
53 Trie root;
54 vector<string> ans;
55
56 int n = ops.size();
57
58 for (int i = 0; i < n; i++) {
59
60 if (ops[i] == "add") {
61 add(&root, args[i]);
62 ans.push_back("null");
63
64 } else if (hunt(&root, args[i], 0)) {
65 ans.push_back("true");
66
67 } else {
68 ans.push_back("false");
69 }
70 }
71
72 return ans;
73}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.