summaryrefslogtreecommitdiff
path: root/extractor/matchings_trie.h
blob: 1fb296936f8e6339da219c7dad411aaa1ddd2edd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#ifndef _MATCHINGS_TRIE_
#define _MATCHINGS_TRIE_

#include <memory>
#include <unordered_map>

#include "phrase.h"
#include "phrase_location.h"

using namespace std;

namespace extractor {

/**
 * Trie node containing all the occurrences of the corresponding phrase in the
 * source data.
 */
struct TrieNode {
  TrieNode(shared_ptr<TrieNode> suffix_link = shared_ptr<TrieNode>(),
           Phrase phrase = Phrase(),
           PhraseLocation matchings = PhraseLocation()) :
      suffix_link(suffix_link), phrase(phrase), matchings(matchings) {}

  // Adds a trie node as a child of the current node.
  void AddChild(int key, shared_ptr<TrieNode> child_node) {
    children[key] = child_node;
  }

  // Checks if a child exists for a given key.
  bool HasChild(int key) {
    return children.count(key);
  }

  // Gets the child corresponding to the given key.
  shared_ptr<TrieNode> GetChild(int key) {
    return children[key];
  }

  shared_ptr<TrieNode> suffix_link;
  Phrase phrase;
  PhraseLocation matchings;
  unordered_map<int, shared_ptr<TrieNode> > children;
};

/**
 * Trie containing all the phrases that can be obtained from a sentence.
 */
class MatchingsTrie {
 public:
  MatchingsTrie();

  virtual ~MatchingsTrie();

  // Returns the root of the trie.
  shared_ptr<TrieNode> GetRoot() const;

 private:
  // Recursively deletes a subtree of the trie.
  void DeleteTree(shared_ptr<TrieNode> root);

  shared_ptr<TrieNode> root;
};

} // namespace extractor

#endif