This problem looks busy at first, but the accepted solution is built around one steady invariant. For 648. Replace Words, the solution in this repository is mainly a trie solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: trie, prefix sums.
The notes already sitting in the source point us in the right direction:
- Approach #1: Prefix Hash
- time: O(sigma(wi^2)), wi is the length of ith word
- space: O(N), N is the length of sentence
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are replaceWords.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- A set is doing the membership or uniqueness work, which keeps the main loop readable.
- Substring checks are convenient but not free, so they are part of the real complexity story.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(N), length of sentence
- Space: O(N), size of trie
Guide
C++ Solution
Your submission
The accepted solution
01//Approach #1: Prefix Hash
02//Runtime: 388 ms, faster than 10.41% of C++ online submissions for Replace Words.
03//Memory Usage: 275.6 MB, less than 14.29% of C++ online submissions for Replace Words.
04//time: O(sigma(wi^2)), wi is the length of ith word
05//space: O(N), N is the length of sentence
06class Solution {
07public:
08 string replaceWords(vector<string>& dict, string sentence) {
09 set<string> dictset;
10 string ans = "";
11 istringstream is(sentence);
12 string token;
13
14 //convert dict from string to set
15 for(string& word : dict){
16 dictset.insert(word);
17 }
18
19 //iterate through sentence
20 while(is >> token){
21 //create "prefix" from current token
22 string prefix = "";
23 for(int i = 1; i <= token.size(); i++){
24 prefix = token.substr(0, i);
25 //find prefix in dictset
26 if(dictset.find(prefix) != dictset.end()){
27 break;
28 }
29 }
30 //add space between tokens
31 if(ans.size() > 0){
32 ans += " ";
33 }
34 // cout << token << " " << prefix << endl;
35 ans += prefix;
36 };
37
38 return ans;
39 }
40};
41
42class TrieNode {
43public:
44 vector<TrieNode*> children;
45 string word;
46 TrieNode(){
47 children = vector<TrieNode*>(26, NULL);
48 word = "";
49 }
50};
51
52//Runtime: 68 ms, faster than 60.86% of C++ online submissions for Replace Words.
53//Memory Usage: 55.8 MB, less than 28.57% of C++ online submissions for Replace Words.
54//time: O(N), length of sentence
55//space: O(N), size of trie
56class Solution {
57public:
58 string replaceWords(vector<string>& dict, string sentence) {
59 TrieNode* root = new TrieNode();
60 //build trie, mark a node as end by setting the attribute "word"
61 for(string& word : dict){
62 TrieNode* cur = root;
63 for(char c : word){
64 if(cur->children[c-'a'] == NULL){
65 cur->children[c-'a'] = new TrieNode();
66 }
67 cur = cur->children[c-'a'];
68 }
69 cur->word = word;
70 }
71
72 string ans;
73 istringstream is(sentence);
74 string token;
75
76 while(is >> token){
77 //find current "token" in the trie
78 TrieNode* cur = root;
79 for(char c : token){
80 //stop search while coming to leaf or finding a "word" that matches it
81 if(cur->children[c-'a'] == NULL || cur->word != ""){
82 break;
83 }
84 cur = cur->children[c-'a'];
85 }
86 if(ans.size() > 0){
87 ans += " ";
88 }
89 ans += (cur->word != "") ? cur->word : token;
90 }
91
92 return ans;
93 }
94};
Cost