日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode 648.单词替换

發布時間:2023/12/1 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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"

注:

  • 輸入只包含小寫字母。
  • 1 <= 字典單詞數 <=1000
  • 1 <=? 句中詞語數?<= 1000
  • 1 <= 詞根長度 <= 100
  • 1 <= 句中詞語長度?<= 1000
  • ?

    思路

    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.单词替换的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。