Trie with map

Let's talk about algorithms!

Moderator: Board moderators

Post Reply
brianfry713
Guru
Posts: 5947
Joined: Thu Sep 01, 2011 9:09 am
Location: San Jose, CA, USA

Trie with map

Post by brianfry713 » Fri Feb 15, 2013 9:14 pm

Code: Select all

#include <iostream>
#include <map>
#include <algorithm>
#include <string>
using namespace std;

string word;

struct trie {
  map<char,trie *> m;
  bool isend;
  trie() {
    isend=false;
  }
};

void insert(trie *&root, int pos) {
  if(word[pos]=='\0') {
    root->isend=true;
    return;
  }
  if(root->m.find(word[pos])==root->m.end())
    root->m[word[pos]]=new trie();
  insert(root->m[word[pos]], pos+1);
}

void del(trie *root) {
  for(map<char,trie *>::iterator it=root->m.begin();it!=root->m.end();it++)
    del(it->second);
  delete root;
}

int find(trie *root, int pos) {
  if(word[pos]=='\0')
    return root->isend;
  if(root->m.find(word[pos])==root->m.end())
    return 0;
  return find(root->m[word[pos]], pos+1);
}

int main() {
  trie *t=new trie();

  word="asdf";
  insert(t, 0);
  word="asdfjkl;";
  insert(t, 0);
  word="jkl;";
  insert(t, 0);

  word="asdf";
  cout << word << " found=" << find(t, 0) << endl;
  word="asdfj";
  cout << word << " found=" << find(t, 0) << endl;

  del(t);
  return 0;
}
Check input and AC output for thousands of problems on uDebug!

Post Reply

Return to “Algorithms”