648. 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:

Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
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

題意:

給定一個句子,還有一組辭典,將句子中含有辭典的詞進行替換(若辭典是句子中某個詞簡寫也需要替換)

例如:

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);
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值