Friday, February 24, 2017

Saving contacts information using tries

Implementation for : https://www.hackerrank.com/challenges/ctci-contacts

Code :
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

struct trie {
    int isleaf;
    int child_cnt;
    trie * t[26];
};

int index(char c) {
    return c-'a';
}
trie * new_node() {
    trie * node = (trie *)malloc(sizeof(trie));
    for (int i = 0; i<26; i++) {
        node->t[i] = NULL;
    }
    node->isleaf = 0;
    int child_cnt = 0;
    return node;
}

void add (trie * root, string s) {
    int len = s.size();
    for (int i = 0; i< len; i++) {
        if (root->t[index(s[i])] == NULL) {
            root->t[index(s[i])] = new_node();
        }
        root->t[index(s[i])]->child_cnt++;
        root = root->t[index(s[i])];
    }
    root->isleaf = 1;
}

int find(trie *root, string s) {
    int len = s.size();
    for (int i = 0; i< len; i++) {
        if (root->t[index(s[i])] == NULL) {
            return 0;
        }
        root = root->t[index(s[i])];
    }
    if (root) {
        return root->child_cnt;
    }
    return 0;
}

int main(){
    int n;
    cin >> n;
    trie * root = new_node();
    for(int a0 = 0; a0 < n; a0++){
        string op;
        string contact;
        cin >> op >> contact;
        if (op == "add") {
            add(root, contact);
        } else {
            cout<<(find(root, contact))<<endl;
        }
    }
    return 0;
}

No comments:

Post a Comment