码迷,mamicode.com
首页 > 其他好文 > 详细

648. Replace Words 替换成为原来的单词

时间:2018-08-24 10:51:51      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:for   exit   color   case   deb   you   原来   结构   其他   

[抄题]:

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 替换成为原来的单词

标签:for   exit   color   case   deb   you   原来   结构   其他   

原文地址:https://www.cnblogs.com/immiao0319/p/9527574.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!