#include <bits/stdc++.h>
using namespace std;
class Trie {
private:
static const int chars = 26;
Trie* child[chars];
bool isLeaf{};
public:
Trie() {
memset(child, 0, sizeof(child));
}
~Trie() {
for (int i = 0; i < chars; i++) {
if (child[i]) {
delete child[i];
}
}
}
void insert(const string& s, int idx = 0) {
if (idx == s.length()) {
isLeaf = true;
} else {
int cur = s[idx] - 'a';
if (child[cur] == nullptr) {
child[cur] = new Trie();
}
child[cur]->insert(s, idx + 1);
}
}
bool wordExists(const string& s, int idx = 0) const {
if (idx == s.size()) return isLeaf;
int cur = s[idx] - 'a';
if (!child[cur]) return false;
return child[cur]->wordExists(s, idx + 1);
}
bool prefixExists(const string& s, int idx = 0) const {
if (idx == s.size()) return true;
int cur = s[idx] - 'a';
if (!child[cur]) return false;
return child[cur]->prefixExists(s, idx + 1);
}
// Check if a word exists by modifying one character
//Problem 3 : hw2
bool findModifiedWord(string s) {
for (int i = 0; i < s.length(); i++) {
char original = s[i];
for (char j = 'a'; j <= 'z'; j++) {
if (j != original) {
s[i] = j;
if (wordExists(s)) {
return true;
}
}
}
s[i] = original;
}
return false;
}
void insertAllSubs(const string& s) {
for (size_t i = 0; i < s.length(); i++) {
for (size_t j = i + 1; j <= s.length(); j++) {
insert(s.substr(i, j - i));
}
}
}
vector<string> findSubs(const string& s, const vector<string>& q) {
Trie subTrie;
subTrie.insertAllSubs(s);
vector<string> ans;
for (const auto& word : q) {
if (subTrie.wordExists(word)) {
ans.push_back(word);
}
}
return ans;
}
};
int main() {
Trie trie;
trie.insert("hello");
trie.insert("world");
vector<string> q = {"hello", "world", "elhabbal", "cr7"};
vector<string> subs = trie.findSubs("helloworldmanarelhabbal", q);
for (const auto& word : subs) {
cout << word << endl;
}
return 0;
}