Skip to content

Create 648. Replace Words #497

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 7, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions 648. Replace Words
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
class TrieNode {
public:
TrieNode* children[26];
bool isEndOfWord;
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < 26; ++i) {
children[i] = nullptr;
}
}
};

class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}

void insert(string word) {
TrieNode* curr = root;
for (char c : word) {
int index = c - 'a';
if (!curr->children[index]) {
curr->children[index] = new TrieNode();
}
curr = curr->children[index];
}
curr->isEndOfWord = true;
}

bool search(string word) {
TrieNode* curr = root;
for (char c : word) {
int index = c - 'a';
if (!curr->children[index]) {
return false;
}
curr = curr->children[index];
}
return curr->isEndOfWord;
}

bool startsWith(string prefix) {
TrieNode* curr = root;
for (char c : prefix) {
int index = c - 'a';
if (!curr->children[index]) {
return false;
}
curr = curr->children[index];
}
return true;
}

string findShortedPrefix(string word) {
TrieNode* curr = root;
for (int i = 0; i < word.length(); ++i) {
int index = word[i] - 'a';
if (!curr->children[index]) {
return word;
}
curr = curr->children[index];
if (curr->isEndOfWord) {
return word.substr(0, i + 1);
}
}
return word;
}
};

class Solution {
public:
string replaceWords(vector<string>& dictionary, string sentence) {
Trie trie;
for (string& word : dictionary) {
trie.insert(word);
}
vector<string> tokens;
string token;
for (char c : sentence) {
if (c == ' ') {
tokens.push_back(token);
token = "";
} else {
token += c;
}
}
tokens.push_back(token);
string result = "";
for (string& token : tokens) {
string prefix = trie.findShortedPrefix(token);
result += prefix + " ";
}
result.pop_back(); // Remove trailing space
return result;
}
};
Loading