website/content.en/ChapterFour/0600~0699/0648.Replace-Words.md
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:
In English, we have a concept called root, which can be followed by some other words to form another longer word—we call this word a successor. For example, the root an, followed by the word other, can form the new word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all successors in the sentence with the roots that form them. If a successor has many roots that can form it, replace it with the shortest root. The requirement is to output the sentence after replacement.
package leetcode
import "strings"
// Solution 1: Hash Table
func replaceWords(dict []string, sentence string) string {
roots := make(map[byte][]string)
for _, root := range dict {
b := root[0]
roots[b] = append(roots[b], root)
}
words := strings.Split(sentence, " ")
for i, word := range words {
b := []byte(word)
for j := 1; j < len(b) && j <= 100; j++ {
if findWord(roots, b[0:j]) {
words[i] = string(b[0:j])
break
}
}
}
return strings.Join(words, " ")
}
func findWord(roots map[byte][]string, word []byte) bool {
if roots[word[0]] == nil {
return false
}
for _, root := range roots[word[0]] {
if root == string(word) {
return true
}
}
return false
}
//Solution 2: Trie
func replaceWords1(dict []string, sentence string) string {
trie := Constructor208()
for _, v := range dict {
trie.Insert(v)
}
words := strings.Split(sentence, " ")
var result []string
word := ""
i := 0
for _, value := range words {
word = ""
for i = 1; i < len(value); i++ {
if trie.Search(value[:i]) {
word = value[:i]
break
}
}
if len(word) == 0 {
result = append(result, value)
} else {
result = append(result, word)
}
}
return strings.Join(result, " ")
}