Re: [閒聊] 每日leetcode

作者: oin1104 (是oin的說)   2024-06-07 14:29:07
※ 引述 《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;
}
};
作者: EliteCaterpi (さくらみこ的綠毛蟲)   2024-06-07 14:35:00
大師 教我
作者: orangeNoob (橘子色的肥肥)   2024-06-07 15:09:00
你好厲害

Links booklink

Contact Us: admin [ a t ] ucptt.com