You are on page 1of 3

#include <iostream>

#include <unordered_map>

class TrieNode {
public:
std::unordered_map<char, TrieNode*> children;
bool isEndOfWord;

TrieNode() : isEndOfWord(false) {}
};

class Trie {
private:
TrieNode* root;

public:
Trie() : root(new TrieNode()) {}

// Insert a word into the Trie


void insert(const std::string& word) {
TrieNode* current = root;

for (char ch : word) {


if (current->children.find(ch) == current->children.end()) {
current->children[ch] = new TrieNode();
}

current = current->children[ch];
}

current->isEndOfWord = true;
}

// Count the number of strings with a specified prefix


int countWithPrefix(const std::string& prefix) {
TrieNode* current = root;

for (char ch : prefix) {


if (current->children.find(ch) == current->children.end()) {
return 0; // Prefix not found
}
current = current->children[ch];
}

return countWordsFromNode(current);
}

private:
// Helper function to count words from a given TrieNode
int countWordsFromNode(TrieNode* node) {
if (!node) {
return 0;
}

int count = node->isEndOfWord ? 1 : 0;

for (const auto& pair : node->children) {


count += countWordsFromNode(pair.second);
}

return count;
}
};

int main() {
Trie trie;

// Insert words into the Trie


trie.insert("apple");
trie.insert("app");
trie.insert("apricot");
trie.insert("bat");
trie.insert("batman");

// Get prefix from user


std::cout << "Enter a prefix to count: ";
std::string prefix;
std::cin >> prefix;

// Count the number of strings with the specified prefix


int count = trie.countWithPrefix(prefix);

std::cout << "Number of strings with prefix '" << prefix << "': " <<
count << std::endl;
return 0;
}

You might also like