题目描述:
给你一个近义词表 synonyms 和一个句子 text , synonyms 表中是一些近义词对 ,你可以将句子 text 中每个单词用它的近义词来替换。
请你找出所有用近义词替换后的句子,按 字典序排序 后返回。
示例 1:
输入:
synonyms = [[“happy”,“joy”],[“sad”,“sorrow”],[“joy”,“cheerful”]],
text = “I am happy today but was sad yesterday”
输出:
[“I am cheerful today but was sad yesterday”,
“I am cheerful today but was sorrow yesterday”,
“I am happy today but was sad yesterday”,
“I am happy today but was sorrow yesterday”,
“I am joy today but was sad yesterday”,
“I am joy today but was sorrow yesterday”]
提示:
0 <= synonyms.length <= 10
synonyms[i].length == 2
synonyms[0] != synonyms[1]
所有单词仅包含英文字母,且长度最多为 10 。
text 最多包含 10 个单词,且单词间用单个空格分隔开。
方法1:
主要思路:解题汇总链接
(1)使用bfs将各个近义词分成一组;
(2)将原来的语句text分割成各个单词,对每个单词找是否存在近义词,若存在近义词,则将对应的近义词可能的组成字符串都压入到结果字符串中;
class Solution {
public:
vector<string> generateSentences(vector<vector<string>>& synonyms, string text) {
vector<string> res;
//将原来的字符串进行分割,获得各个单词
vector<string>words;
int index=0;
while(index<text.size()){
int pos=index;
while(pos<text.size()&&text[pos]!=' '){
++pos;
}
words.push_back(text.substr(index,pos-index));
index=pos+1;
}
vector<vector<string>> sts;//存储各个近义词集合
//给出的近义词建立邻接图
unordered_map<string,vector<string>> graph;
for(auto&it:synonyms){
graph[it[0]].push_back(it[1]);
graph[it[1]].push_back(it[0]);
}
unordered_set<string> sign;//标识已经使用过的字符串
unordered_map<string,int>mp;//各个近义词所在的集合的索引
for(auto&it:graph){
if(sign.count(it.first)){//当前单词已经使用过
continue;
}
sign.insert(it.first);//标识当前单词已经使用过
vector<string>cur_strs;//存储当前近义词集合
cur_strs.push_back(it.first);
queue<string>q;//bfs队列
q.push(it.first);
while(!q.empty()){
string cur_str_node=q.front();
q.pop();
mp[cur_str_node]=sts.size();//当前近义词在所在近义词集合的索引
for(string&str:graph[cur_str_node]){//各个可能的近义词
if(sign.count(str)){
continue;
}
sign.insert(str);
q.push(str);
cur_strs.push_back(str);
}
}
sts.push_back(cur_strs);//将当前近义词集合压入集合数组中
}
res.push_back("");//存储结果
for(int i=0;i<words.size();++i){//判断各个单词
if(mp.count(words[i])==0){//说明当前单词不存在近义词
for(string&str:res){
if(str.size()==0){
str+=words[i];
}
else{
str+=" "+words[i];
}
}
}
else{//将各个近义词可能组成的新的字符串压入到结果数组中
vector<string>& tmp=sts[mp[words[i]]];
int cur_size=res.size();
for(int j=1;j<tmp.size();++j){
for(int k=0;k<cur_size;++k){
if(res[k].size()==0){
res.push_back(res[k]+tmp[j]);
}
else{
res.push_back(res[k]+" "+tmp[j]);
}
}
}
for(int k=0;k<cur_size;++k){
if(res[k].size()==0){
res[k]+=tmp[0];
}
else{
res[k]+=" "+tmp[0];
}
}
}
}
sort(res.begin(),res.end());//排序
return res;
}
};