Friday, 21 October 2016

Contacts (CTCI)

Problem: Contacts

struct Trie{
    int cnt;
    Trie *child[26];
    Trie(): cnt(0){};
};

Trie *root;

int insert(string s, int find)
{
    int sl = s.length();
    Trie *head = root;
    for(int i=0;i<sl;i++)
    {
        int index = s[i]-'a';
        if(head->child[index]==NULL)
        {
            if(find) return 0;
            head->child[index] = new Trie();
        }
        if(!find) head->child[index]->cnt++;
        head = head->child[index];        
    }
    return head->cnt;    
}

int main(){
    int n;
    root = new Trie();
    cin >> n;
    for(int a0 = 0; a0 < n; a0++){
        string op;
        string contact;
        cin >> op >> contact;
        if(op=="add") insert(contact, 0);
        else cout<<insert(contact, 1)<<endl;
    }
    return 0;
}

No comments:

Post a Comment