93 單詞替換(648)
作者:
晚於: 2020-09-09 12:00:00後提交分數乘係數50%
問題描述 :
在英語中,我們有一個叫做 詞根(root)的概念,它可以跟著其他一些片語成另一個較長的單詞——我們稱這個詞為 繼承詞(successor)。例如,詞根an,跟隨著單詞 other(其他),可以形成新的單詞 another(另一個)。
現在,給定一個由許多詞根組成的詞典和一個句子。你需要將句子中的所有繼承詞用詞根替換掉。如果繼承詞有許多可以形成它的詞根,則用最短的詞根替換它。
你需要輸出替換之後的句子。
示例 1:
輸入:dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
輸出:"the cat was rat by the bat"
示例 2:
輸入:dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
輸出:"a a b c"
示例 3:
輸入:dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
輸出:"a a a a a a a a bbb baba a"
示例 4:
輸入:dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
輸出:"the cat was rat by the bat"
示例 5:
輸入:dictionary = ["ac","ab"], sentence = "it is abnormal that this solution is accepted"
輸出:"it is ab that this solution is ac"
可使用以下main函式:
int main()
{
int n;
vector<string> dict;
string sentence,word;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>word;
dict.push_back(word);
}
cin.get();
getline(cin, sentence);
string res=Solution().replaceWords(dict, sentence);
cout<<res;
}
輸入說明 :
首先輸入字典的單詞數n,
然後輸入n個單詞,每個單詞均由小寫字母組成,長度在1到100之間。
最後輸入一個字串sentence,
1 <= sentence.length <= 10^6
sentence 僅由小寫字母和空格組成。
sentence 中單詞的總量在範圍 [1, 1000] 內。
sentence 中每個單詞的長度在範圍 [1, 1000] 內。
sentence 中單詞之間由一個空格隔開。
sentence 沒有前導或尾隨空格。
輸出說明 :
輸出一個字串
輸入範例 :
輸出範例 :
#include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; class Solution { public: string replaceWords(vector<string>& dict, string& sentence) { unordered_map<string,int> map; for(auto i:dict) map[i]=1; string res=""; for(int i=0;i<sentence.size();) { int j=i,flag=0; string temp=""; while(j<sentence.size()&&sentence[j]!=' ') { if(!flag) temp+=sentence[j]; if(map[temp]) flag=1; j++; } res+=temp; if(j<sentence.size()) res+=" "; i=j+1; } return res; } }; int main() { int n; vector<string> dict; string sentence,word; cin>>n; for(int i=0; i<n; i++) { cin>>word; dict.push_back(word); } cin.get(); getline(cin, sentence); string res=Solution().replaceWords(dict, sentence); cout<<res; }