Quick actions

cmd+k|ctrl+k

Navigation

Languages

Trie

Snippet info

Language

Cpp

Visibility

public

Author

kevin-y-li

Created

2017-05-10T02:46:42Z

Updated

2017-05-10T04:21:13Z

#include <iostream>
#include <map>
#include <regex>
#include <string>

using namespace std;


struct Node {
    map<char, Node*> children;
    bool terminal;
};

bool isTokenDelimiter(char c) {
    return c < 'a' || c > 'z';
}

bool isWordDelimiter(char c) {
    return isTokenDelimiter(c) && (c < 'A' || c > 'Z') && (c < '-' || c > ':') && c != '_';
}

void insertToken(Node *root, string token) {
    cout << "insert token: " << token << endl;
    for (int i = 0; i < token.length(); ++i) {
        if (root->children.find(token[i]) == root->children.end()) {
            root->children.emplace(token[i], new Node());
        }
        root = root->children[token[i]];
    }
    root->terminal = true;
}

void insertWord(Node *root, string word) {
    cout << "insert word: " << word << endl;
    for (int i = 0; i < word.length(); ++i) {
        if (isTokenDelimiter(word[i])) {
            insertToken(root, word.substr(i));
        }
    }
    insertToken(root, word);
}



int countTokens(Node *root) {
    int count = root->terminal ? 1 : 0;
    for (auto it : root->children) {
        count += countTokens(it.second);
    }
    return count;
}

int main() {
    Node *root = new Node();
    
    string word;
    char c;
    while (cin.get(c)) {
        if (isWordDelimiter(c)) {
            insertWord(root, word);
            word.clear();
        } else {
            word += c;
        }
    }
    cout << countTokens(root);
    return 0;
}
INFO