In English, we have a concept called root
, which can be followed by some other words to form another longer word - let's call this word successor
. For example, the root an
, followed by other
, which can form another word another
.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor
in the sentence with the root
forming it. If a successor
has many roots
can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
Input: dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"
Note:
- The input will only have lower-case letters.
- 1 <= dict words number <= 1000
- 1 <= sentence words number <= 1000
- 1 <= root length <= 100
- 1 <= sentence words length <= 1000
几乎可以说是裸的Trie。用dic中的单词建立字典树(注意字典树动态生成大小,直接开数组或map会MLE)。句子中的每个单词在字典树中按查询的方式走,遇到字典中某个单词的结尾就返回这个单词,遇到没有结点时就直接把该单词完整输出即可。 给出一行含空格的字符串还是直接用stringstream处理比较方便。
1 class Solution { 2 public: 3 struct Trie { 4 bool isWord; 5 Trie* child[26]; 6 7 Trie(bool isWord) : isWord(isWord) { 8 memset(child, 0, sizeof(child)); 9 } 10 11 void addWord(string& s) { 12 Trie* cur = this; 13 for (char c : s) { 14 Trie* next = cur->child[c - 'a']; 15 if (next == nullptr) { 16 next = cur->child[c - 'a'] = new Trie(false); 17 } 18 cur = next; 19 } 20 cur->isWord = true; 21 } 22 23 ~Trie() { 24 for (int i = 0; i < 26; ++i) { 25 if (child[i]) { 26 delete child[i]; 27 } 28 } 29 } 30 }; 31 string findRoot(Trie& root, string& s) { 32 Trie* cur = &root; 33 for (int i = 0; i < s.size(); ++i) { 34 char c = s[i]; 35 cur = cur->child[c - 'a']; 36 if (cur == nullptr) { 37 return s; 38 } 39 if (cur->isWord) { 40 return s.substr(0, i + 1); 41 } 42 } 43 return s; 44 } 45 string replaceWords(vector<string>& dict, string sentence) { 46 Trie tem(false); 47 string res; 48 for(int i=0;i<dict.size();i++) 49 { 50 tem.addWord(dict[i]); 51 } 52 stringstream ss(sentence); 53 string s; 54 while(ss>>s) 55 { 56 if(res.size()) 57 res+=" "; 58 res+=findRoot(tem,s); 59 } 60 return res; 61 } 62 };