Skip to content

Conversation

@karygauss03
Copy link
Owner

No description provided.

Comment on lines +1 to +64
struct TrieNode {
char data;
bool isPrefix;
TrieNode* children[26];
};

class Solution {
private:
vector<string> tokenizer(string& line) {
vector<string> tokens;
stringstream check1(line);
string intermediate;
while (getline(check1, intermediate, ' ')) {
tokens.push_back(intermediate);
}
return tokens;
}

public:
string replaceWords(vector<string>& dict, string sentence) {
sort(dict.begin(), dict.end());
int n = sentence.size();
string tmp = "";
string ans = "";
for (int i = 0 ; i < n ; i++){
if (sentence[i] == ' '){
bool flag = false;
for (auto &s : dict){
if (s == tmp.substr(0, s.size())){
ans += s;
ans += ' ';
flag = true;
break;
}
}
if (!flag){
ans += tmp;
ans += ' ';
}
tmp = "";
}
else {
tmp += sentence[i];
TrieNode nodepool[100000]; // Pool of 100K TrieNodes
TrieNode* root; // Root of Trie
int poolcount; // Always points to next free TrieNode

void init() {
poolcount = 0;
root = &nodepool[poolcount++];
root->data = '/';
root->isPrefix = false;
for (int i = 0; i < 26; ++i) {
root->children[i] = nullptr;
}
}

TrieNode* getNode(char c) {
TrieNode* node = &nodepool[poolcount++];
node->data = c;
node->isPrefix = false;
for (int i = 0; i < 26; ++i) {
node->children[i] = nullptr;
}
return node;
}

void insert(string& word) {
TrieNode* current = root;
for (auto& c : word) {
if (current->children[c - 'a'] == nullptr) {
current->children[c - 'a'] = getNode(c);
}
current = current->children[c - 'a'];
}
bool flag = false;
for (auto &s : dict){
if (s == tmp.substr(0, s.size())){
ans += s;
ans += ' ';
flag = true;
current->isPrefix = true;
}

bool search(string& prefix) {
TrieNode* current = root;
for (char& c : prefix) {
if (current->children[c - 'a'] == nullptr) {
return false;
}
current = current->children[c - 'a'];
}
return current->isPrefix;
}
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TO ME, please try to have a Trie class separately to be used in future problems directly.

@karygauss03 karygauss03 merged commit 9006779 into main Jun 7, 2024
@karygauss03 karygauss03 deleted the 648.-Replace-Words branch June 7, 2024 09:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant