Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- /*
- * Complete the contacts function below.
- */
- class Trie
- {
- public:
- bool endmark;
- Trie *next[26];
- Trie()
- {
- endmark = false;
- for(int i = 0; i < 26; i++)
- next[i] = NULL;
- }
- void insert(string s);
- int findMatch(string s);
- void _count(Trie *curr, int* cnt);
- bool _search(string s);
- };
- void Trie::_count(Trie *curr, int* cnt)
- {
- if(curr == NULL)
- return;
- if(curr->endmark)
- {
- //cout << curr->endmark << endl;
- (*cnt)++;
- }
- for(int i = 0; i < 25; i++)
- {
- _count(curr->next[i],cnt);
- }
- }
- void Trie::insert(string s)
- {
- Trie *curr = this;
- for(int i = 0; i < s.size(); i++)
- {
- int id = s[i]-'a';
- if(curr->next[id] == NULL)
- curr->next[id] = new Trie();
- curr = curr->next[id];
- }
- curr->endmark = true;
- }
- bool Trie::_search(string s)
- {
- Trie *curr = this;
- for(int i = 0; i < s.size(); i++)
- {
- int id = s[i]-'a';
- if(curr->next[id] == NULL)
- return false;
- curr = curr->next[id];
- }
- return curr->endmark;
- }
- int Trie::findMatch(string s)
- {
- int cnt = 0;
- Trie *curr = this;
- for(int i = 0; i < s.size(); i++)
- {
- int id = s[i]-'a';
- if(curr->next[id] == NULL)
- return 0;
- curr = curr->next[id];
- }
- _count(curr,&cnt);
- return cnt;
- }
- vector<int> contacts(vector<vector<string>> queries) {
- /*
- * Write your code here.
- */
- Trie *t = new Trie();
- vector<int> result;
- for(int i = 0; i < queries.size(); i++)
- {
- string s1, s2;
- s1 = queries[i][0];
- s2 = queries[i][1];
- if(s1 == "add")
- {
- t->insert(s2);
- }
- else if(s1 == "find")
- {
- int cnt = t->findMatch(s2);
- result.push_back(cnt);
- }
- else if(s1 == "search")
- {
- cout << t->_search(s2) << endl;
- }
- }
- return result;
- }
- int main()
- {
- vector<vector<string>> queries;
- int n;
- cin >> n;
- while(n--)
- {
- string s1, s2;
- vector<string> a;
- cin >> s1 >> s2;
- a.push_back(s1);
- a.push_back(s2);
- queries.push_back(a);
- }
- vector<int> result = contacts(queries);
- for(int i = 0; i < result.size(); i++)
- {
- cout << result[i] << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement