[抄题]:
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(); } }