Code & Func
2019-11-12

第8天。

今天的题目是 Replace Words


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:

1
Input: dict = ["cat", "bat", "rat"]
2
sentence = "the cattle was rattled by the battery"
3
Output: "the cat was rat by the bat"

Note:

  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 1 <= sentence words length <= 1000

看到题目给出了一个字符串字典,然后要根据单词中是否包含字典中的前缀来生成结果,想都不用想,就是用前缀树/字典树来做,关于前缀树的介绍可以看 https://oi-wiki.org/string/trie/

首先先根据字典建立字典树,然后根据空格分隔单词,然后检查是否有前缀,如果没有前缀就将原始的单词插入结果中,如果有,则将前缀插入。由于在进行检查时,每次从一个节点跳到其子节点时都会检查者是否是一个在词典出现的前缀,所以所求的前缀一定是最短的。

具体代码如下:

1
struct Node {
2
struct Node* childs[26];
3
bool isLeaf;
4
Node():isLeaf(false){
5
for(int i = 0;i < 26;i++) childs[i] = nullptr;
6
}
7
~Node() {
8
for(int i = 0;i < 26;i++) if (childs[i]) delete childs[i];
9
}
10
11
};
12
13
void insert(struct Node *root, string &s) {
14
for(int i = 0, size = s.size(); i < size; i++) {
15
int index = s[i] - 'a';
44 collapsed lines
16
if (root->childs[index] == nullptr) root->childs[index] = new Node;
17
root = root->childs[index];
18
}
19
root->isLeaf = true;
20
}
21
int getMinLen(struct Node *root, string &sentence, int beg, int end) {
22
for(int i = beg;i < end; i++) {
23
int index = sentence[i] - 'a';
24
if (root->childs[index] == nullptr) return end;
25
root = root->childs[index];
26
if (root->isLeaf) return i + 1;
27
}
28
return end;
29
}
30
string replaceWords(vector<string>& dict, string sentence) {
31
// sort(dict.begin(), dict.end());
32
33
// build dict tree
34
struct Node *root = new Node();
35
for(int i = 0;i < dict.size(); ++i) {
36
insert(root, dict[i]);
37
}
38
39
struct Node * p = root;
40
41
// parse sentence
42
string res, word;
43
int beg = 0;
44
for(int i = 0, size = sentence.size(); i < size; i++) {
45
if (sentence[i] == ' ') {
46
int end = getMinLen(root, sentence, beg, i);
47
for(int j = beg;j < end; j++) res.push_back(sentence[j]);
48
res.push_back(' ');
49
beg = i + 1;
50
word = "";
51
52
}
53
}
54
55
int end = getMinLen(root, sentence, beg, sentence.size());
56
for(int j = beg;j < end; j++) res.push_back(sentence[j]);
57
delete root;
58
return res;
59
}
上一条动态