648 Replace Words

1. Question

In English, we have a concept calledroot, which can be followed by some other words to form another longer word - let's call this wordsuccessor. For example, the rootan, followed byother, which can form another wordanother.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all thesuccessorin the sentence with therootforming it. If asuccessorhas manyrootscan 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
4
Output: "the cat was rat by the bat"
Copied!
Note:
  1. 1.
    The input will only have lower-case letters.
  2. 2.
    1 <= dict words number <= 1000
  3. 3.
    1 <= sentence words number <= 1000
  4. 4.
    1 <= root length <= 100
  5. 5.
    1 <= sentence words length <= 1000

2. Implementation

(1) Trie
思路: 很典型的查询prefix的应用,所以用trie很适合,只要在trieNode的基础上加入字典里的string所对应的index即可
1
class Solution {
2
class TrieNode {
3
char val;
4
int index;
5
boolean isWord;
6
TrieNode[] childNode;
7
8
public TrieNode(char val) {
9
this.val = val;
10
index = -1;
11
childNode = new TrieNode[26];
12
}
13
}
14
15
class Trie {
16
TrieNode root;
17
18
public Trie() {
19
root = new TrieNode(' ');
20
}
21
22
public void insert(String word, int index) {
23
if (word == null || word.length() == 0) {
24
return;
25
}
26
27
TrieNode curNode = root;
28
29
for (char c : word.toCharArray()) {
30
int pos = c - 'a';
31
if (curNode.childNode[pos] == null) {
32
curNode.childNode[pos] = new TrieNode(c);
33
}
34
curNode = curNode.childNode[pos];
35
}
36
curNode.isWord = true;
37
curNode.index = index;
38
}
39
40
public int searchPrefix(String word) {
41
if (word == null || word.length() == 0) {
42
return -1;
43
}
44
45
TrieNode curNode = root;
46
47
for (char c : word.toCharArray()) {
48
int pos = c - 'a';
49
if (curNode.childNode[pos] == null) {
50
return -1;
51
}
52
else if (curNode.childNode[pos].isWord){
53
return curNode.childNode[pos].index;
54
}
55
curNode = curNode.childNode[pos];
56
}
57
return curNode.index;
58
}
59
}
60
public String replaceWords(List<String> dict, String sentence) {
61
if (dict.size() == 0 || sentence == null || sentence.length() == 0) {
62
return "";
63
}
64
65
Trie trie = new Trie();
66
67
for (int i = 0; i < dict.size(); i++) {
68
trie.insert(dict.get(i), i);
69
}
70
71
String[] words = sentence.split("\\s+");
72
73
for (int i = 0; i < words.length; i++) {
74
int index = trie.searchPrefix(words[i]);
75
76
if (index != -1) {
77
words[i] = dict.get(index);
78
}
79
}
80
81
StringBuilder res = new StringBuilder();
82
83
for (int i = 0; i < words.length - 1; i++) {
84
res.append(words[i]);
85
res.append(" ");
86
}
87
88
res.append(words[words.length - 1]);
89
return res.toString();
90
}
91
}
Copied!

3. Time & Space Complexity

Trie: 时间复杂度O(n * m), n是dict里面string的个数,m是string的平均长度。 空间复杂度O(nm)