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
題意:
給定一個句子,還有一組辭典,將句子中含有辭典的詞進行替換(若辭典是句子中某個詞簡寫也需要替換)
例如:
Input: dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"題解:
** 需要把字典中所有詞存入HashSet,以提高查找效率**
先將句子的每個詞以" "分開,成一個數組,然後歷遍該數組中的每個詞,並將該詞由前往後進行簡寫枚舉,例如:
abcd -> a, ab, abc, abcd
若枚舉的詞符合字典中某個詞時,則進行替換,歷遍所有詞後,進行答案拼裝
package LeetCode.Medium;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ReplaceWords {
public String replaceWords(List<String> dict, String sentence) {
if(dict == null || dict.size() == 0 || sentence == null || sentence.equals("") || sentence.length() == 0){
return "";
}
//利用HashSet來做辭典,避免超時的問題(效率較高)
Set<String> dict_set = new HashSet<String>();
//將dict所有結果存入HashSet
dict_set.addAll(dict);
//以空白來切割
String[] words = sentence.split(" ");
for(int i = 0; i < words.length; i ++) {
String word = words[i];
//將字符串進行縮寫的枚舉(從前面枚舉至後面)
for(int j = 0; j <= word.length(); j ++) {
String sub_word = word.substring(0, j);
//若縮寫有在辭典中則進行替換
if(dict_set.contains(sub_word) == true) {
words[i] = sub_word;
break;
}
}
}
//組查答案
String result = "";
for(int i = 0; i < words.length; i ++) {
result += words[i] + " ";
}
//別忘了最後一個空格要去掉
return result.substring(0, result.length() - 1);
}
}