Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (是oin的說)時間1年前 (2024/06/07 14:29), 編輯推噓2(200)
留言2則, 2人參與, 1年前最新討論串329/1550 (看更多)
※ 引述 《Rushia (早瀬ユウカの体操服)》 之銘言: :   : https://leetcode.com/problems/replace-words/description : 648. Replace Words : 給你一個字串列表dictionary和一個字串sentence,sentence裡面有很多單字,這些單字 : 被空白分割,有些單字是從其他單字的字首延伸的例如:helpful = help+ful 若 : sentence裡面的單字字首存在於dictionary我們可以把原單字替換成較短的字首,若 : 存在多個字首則取最短,求出替換完的句子長什麼樣子。 :   : Example 1: : Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled : by the battery" : Output: "the cat was rat by the bat" :   : 思路: : 1.前面忘了中間忘了憑印象手刻一個字典樹,先把所有字根加入字典樹。 : 2.接下來把sentence依照空白切成單字,如果這個單字在字典樹裡面就加入第一個找到的 : 字根,找不到就返回原單字。 : 3.把結果集串起來用空白分割。 :   思路 : c++沒有內建字典樹 我懶得刻 所以用unordered set 裡面放 string 代替 然後每次進來的字母都去找set裡面有沒有 有的話就加進res 並且跳到下一個空格 就好了 好想姆咪 class Solution { public: string replaceWords(vector<string>& dictionary, string sentence) { int len = dictionary.size(); unordered_set<string> paper; for(int i = 0 ; i < len ; i ++) { paper.insert(dictionary[i]); } int slen = sentence.size(); string res ; for(int i = 0 ; i < slen ; i ++) { string k ; while(i < slen && sentence[i] != ' ') { k += sentence[i]; i++; if(paper.find(k) != paper.end()) { while(i < slen && sentence[i] != ' ') { i++; } } } res += k; res += " "; } res.pop_back(); return res; } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.12.156.41 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1717741749.A.88D.html

06/07 14:35, 1年前 , 1F
大師 教我
06/07 14:35, 1F

06/07 15:09, 1年前 , 2F
你好厲害
06/07 15:09, 2F
文章代碼(AID): #1cOgYrYD (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cOgYrYD (Marginalman)