648. Replace Words
来源:互联网 发布:网络电视怎么放不出来 编辑:程序博客网 时间:2024/05/29 14:45
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); }}
- 648. Replace Words
- Leetcode--648. Replace Words
- 648. Replace Words
- leetcode 648. Replace Words
- 648. Replace Words
- 648. Replace Words
- 648. Replace Words
- leetcode-648. Replace Words
- leetcode 648. Replace Words
- leetcode 648. Replace Words
- 648. Replace Words
- 648. Replace Words
- Replace Words
- LeetCode 648. Replace Words 字典树练习
- leetcode 648. Replace Words 字典树
- 【LeetCode】648.Replace Words(Medium)解题报告
- leetcode 648. Replace Words 公共前缀
- LeetCode.648 Replace Words
- linux下安装mongodb
- SpringMvc+jxl实现excel导入导出
- UML类图讲解
- 5.IDA-文本搜索、二进制搜索(16进制字节序列)、替换16进制
- scrt_sfx安装
- 648. Replace Words
- -----广搜 POJ 3278-Catch That Cow
- 树莓派3B内核移植
- HDU 6070 Dirt Ratio [二分+线段树]
- css组合器
- Lightoj 1166 Old Sorting(大水题)
- ZOJ 3573 Under Attack (线段树两边维护最大值)
- 划分整数(小水题+小学数学)
- Machine Learning In Action