Skip to content

Commit 76908ed

Browse files
authored
Create 648. Replace Words (#497)
2 parents a365410 + 8e901b6 commit 76908ed

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

648. Replace Words

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
class TrieNode {
2+
public:
3+
TrieNode* children[26];
4+
bool isEndOfWord;
5+
TrieNode() {
6+
isEndOfWord = false;
7+
for (int i = 0; i < 26; ++i) {
8+
children[i] = nullptr;
9+
}
10+
}
11+
};
12+
13+
class Trie {
14+
public:
15+
TrieNode* root;
16+
Trie() {
17+
root = new TrieNode();
18+
}
19+
20+
void insert(string word) {
21+
TrieNode* curr = root;
22+
for (char c : word) {
23+
int index = c - 'a';
24+
if (!curr->children[index]) {
25+
curr->children[index] = new TrieNode();
26+
}
27+
curr = curr->children[index];
28+
}
29+
curr->isEndOfWord = true;
30+
}
31+
32+
bool search(string word) {
33+
TrieNode* curr = root;
34+
for (char c : word) {
35+
int index = c - 'a';
36+
if (!curr->children[index]) {
37+
return false;
38+
}
39+
curr = curr->children[index];
40+
}
41+
return curr->isEndOfWord;
42+
}
43+
44+
bool startsWith(string prefix) {
45+
TrieNode* curr = root;
46+
for (char c : prefix) {
47+
int index = c - 'a';
48+
if (!curr->children[index]) {
49+
return false;
50+
}
51+
curr = curr->children[index];
52+
}
53+
return true;
54+
}
55+
56+
string findShortedPrefix(string word) {
57+
TrieNode* curr = root;
58+
for (int i = 0; i < word.length(); ++i) {
59+
int index = word[i] - 'a';
60+
if (!curr->children[index]) {
61+
return word;
62+
}
63+
curr = curr->children[index];
64+
if (curr->isEndOfWord) {
65+
return word.substr(0, i + 1);
66+
}
67+
}
68+
return word;
69+
}
70+
};
71+
72+
class Solution {
73+
public:
74+
string replaceWords(vector<string>& dictionary, string sentence) {
75+
Trie trie;
76+
for (string& word : dictionary) {
77+
trie.insert(word);
78+
}
79+
vector<string> tokens;
80+
string token;
81+
for (char c : sentence) {
82+
if (c == ' ') {
83+
tokens.push_back(token);
84+
token = "";
85+
} else {
86+
token += c;
87+
}
88+
}
89+
tokens.push_back(token);
90+
string result = "";
91+
for (string& token : tokens) {
92+
string prefix = trie.findShortedPrefix(token);
93+
result += prefix + " ";
94+
}
95+
result.pop_back(); // Remove trailing space
96+
return result;
97+
}
98+
};

0 commit comments

Comments
 (0)