Leetcode 648.单词替换
單詞替換
在英語中,我們有一個叫做?詞根(root)的概念,它可以跟著其他一些詞組成另一個較長的單詞——我們稱這個詞為?繼承詞(successor)。例如,詞根an,跟隨著單詞?other(其他),可以形成新的單詞?another(另一個)。
現在,給定一個由許多詞根組成的詞典和一個句子。你需要將句子中的所有繼承詞用詞根替換掉。如果繼承詞有許多可以形成它的詞根,則用最短的詞根替換它。
你需要輸出替換之后的句子。
示例 1:
輸入: dict(詞典) = ["cat", "bat", "rat"]
sentence(句子) = "the cattle was rattled by the battery"
輸出: "the cat was rat by the bat"
注:
?
思路
Intuition
For each word in the sentence, we'll look at successive prefixes and see if we saw them before.
Algorithm
Store all the roots in a Set structure. Then for each word, look at successive prefixes of that word. If you find a prefix that is a root, replace the word with that prefix. Otherwise, the prefix will just be the word itself, and we should add that to the final sentence answer.
public String[] split(String regex)根據給定的正則表達式的匹配來拆分此字符串。
?
然后就要明確正則表達式的含義了:
\\s表示 空格,回車,換行等空白符,
+號表示一個或多個的意思
?
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Solution {
public String replaceWords(List<String> roots, String sentence) {
Set<String> rootset = new HashSet();
for (String root: roots) rootset.add(root);
StringBuilder ans = new StringBuilder();
for (String word: sentence.split("\\s+")) {
String prefix = "";
for (int i = 1; i <= word.length(); ++i) {
prefix = word.substring(0, i);
if (rootset.contains(prefix)) break;
}
if (ans.length() > 0) ans.append(" ");
ans.append(prefix);
}
return ans.toString();
}
}
轉載于:https://www.cnblogs.com/kexinxin/p/10383069.html
總結
以上是生活随笔為你收集整理的Leetcode 648.单词替换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: luogu P1880 [NOI1995
- 下一篇: 理解总结篇—List、Set、Map