1. 程式人生 > >648. Replace Words 替換成為原來的單詞

648. Replace Words 替換成為原來的單詞

and bsp ati ech 解法 叠代 原來 臺詞 gif

[抄題]:

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"

[暴力解法]:

時間分析:

空間分析:

[優化後]:

時間分析:

空間分析:

[奇葩輸出條件]:

[奇葩corner case]:

[思維問題]:

不知道怎麽取單詞前半截:.substring都忘了,實在是太弱了。

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

[一句話思路]:

[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

substring包左不包右,所以i需要 i <= word.length多加一位

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分鐘肉眼debug的結果]:

[總結]:

取前半截用substring,而且右邊界的i不包,要包就要加<=i的等號

[復雜度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:叠代/遞歸/分治/貪心]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

[是否頭一次寫此類driver funcion的代碼] :

[潛臺詞] :

技術分享圖片
class Solution {
    public String replaceWords(List<String> dict, String sentence) {
        //corner case
      if (dict == null || sentence.length() == 0) 
        return "";
      //initialization: set
      Set<String> set = new HashSet<String>();
      
      //put all the words into set
      for (int i = 0; i < dict.size(); i++) {
        set.add(dict.get(i));
      }
      
      //append the new result
      StringBuilder sb = new StringBuilder();
      String[] words = sentence.split("\\s+");
      for (String word : words) {
        String prefix = "";
        for (int i = 1; i <= word.length(); i++) {
          prefix = word.substring(0, i);
          if (set.contains(prefix)) break;
        }
        sb.append(" " + prefix);
      }
      
      //return
      return sb.deleteCharAt(0).toString();
    }
}
View Code

648. Replace Words 替換成為原來的單詞