力扣 648. 单词替换
生活随笔
收集整理的這篇文章主要介紹了
力扣 648. 单词替换
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目
在英語中,我們有一個叫做 詞根(root) 的概念,可以詞根后面添加其他一些詞組成另一個較長的單詞——我們稱這個詞為 繼承詞(successor)。例如,詞根an,跟隨著單詞 other(其他),可以形成新的單詞 another(另一個)。
現(xiàn)在,給定一個由許多詞根組成的詞典 dictionary 和一個用空格分隔單詞形成的句子 sentence。你需要將句子中的所有繼承詞用詞根替換掉。如果繼承詞有許多可以形成它的詞根,則用最短的詞根替換它。
你需要輸出替換之后的句子。
示例
輸入:dictionary = [“cat”,“bat”,“rat”], sentence = “the cattle was rattled by the battery”
輸出:“the cat was rat by the bat”
輸入:dictionary = [“a”,“b”,“c”], sentence = “aadsfasf absbs bbab cadsfafs”
輸出:“a a b c”
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/replace-words
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。
方法1:哈希表模擬
Java實現(xiàn)
class Solution {public String replaceWords(List<String> dictionary, String sentence) {Set<String> set = new HashSet<>();for (String d : dictionary) set.add(d);String[] strs = sentence.split(" ");for (int i = 0; i < strs.length; i++) {String str = strs[i];for (int j = 0; j < str.length(); j++) {if (set.contains(str.substring(0, j + 1))) {strs[i] = str.substring(0, j + 1);break;}}}return String.join(" ", strs);} }總結
以上是生活随笔為你收集整理的力扣 648. 单词替换的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: seek()
- 下一篇: 智慧养老解决方案的优点和不足