题目描述:
给你一个「短语」列表 phrases,请你帮忙按规则生成拼接后的「新短语」列表。
「短语」(phrase)是仅由小写英文字母和空格组成的字符串。「短语」的开头和结尾都不会出现空格,「短语」中的空格不会连续出现。
「前后拼接」(Before and After puzzles)是合并两个「短语」形成「新短语」的方法。我们规定拼接时,第一个短语的最后一个单词 和 第二个短语的第一个单词 必须相同。
返回每两个「短语」 phrases[i] 和 phrases[j](i != j)进行「前后拼接」得到的「新短语」。
注意,两个「短语」拼接时的顺序也很重要,我们需要同时考虑这两个「短语」。另外,同一个「短语」可以多次参与拼接,但「新短语」不能再参与拼接。
请你按字典序排列并返回「新短语」列表,列表中的字符串应该是 不重复的 。
示例 1:
输入:phrases = [“writing code”,“code rocks”]
输出:[“writing code rocks”]
示例 2:
输入:phrases = [“mission statement”,
“a quick bite to eat”,
“a chip off the old block”,
“chocolate bar”,
“mission impossible”,
“a man on a mission”,
“block party”,
“eat my words”,
“bar of soap”]
输出:[“a chip off the old block party”,
“a man on a mission impossible”,
“a man on a mission statement”,
“a quick bite to eat my words”,
“chocolate bar of soap”]
示例 3:
输入:phrases = [“a”,“b”,“a”]
输出:[“a”]
提示:
1 <= phrases.length <= 100
1 <= phrases[i].length <= 100
通过次数1,266提交次数3,525
方法1:
主要思路:解题汇总链接
(1)使用哈希来快速确定每个字符串的首个单词和最后一个单词;
(2)使用set来去除重复的拼接字符串;
(3)先对每个字符串进行分解,找出首个单词和最后一个单词,和对应的字符串的索引一起存储到对应的哈希中;
(4)遍历存储最后一个单词的哈希,找每个元素的字符串是否在存储第一个单词的哈希中存在,若存在则生成对应的字符串,存储到set中来去重;
class Solution {
public:
vector<string> beforeAndAfterPuzzles(vector<string>& phrases) {
//初始化存储字符串首个单词和最后一个单词的哈希
unordered_map<string,vector<int>> mp_front;
unordered_map<string,vector<int>> mp_back;
int index=0;//每个字符换的索引
for(string& str:phrases){
int pos=0;//用于找出第一个单词
while(pos!=str.size()&&str[pos]!=' '){
++pos;
}
mp_front[str.substr(0,pos)].push_back(index);//将当前字符串的第一单词和对应的索引存储到对应的哈希中
//找出最后一个单词
pos=str.size()-1;
while(pos>=0&&str[pos]!=' '){
--pos;
}
mp_back[str.substr(pos+1)].push_back(index);//将当前字符串的最后一个单词和对应的索引存储到对应的哈希中
++index;
}
set<string> st;//存储拼接生成的字符串,可以实现去重
//遍历存储最后一个单词的哈希
for(auto& it:mp_back){
if(mp_front.count(it.first)){//字符串的最后一个单词存储对应的作为第一个单词的字符串
//合并对应的字符串
for(int& i:mp_back[it.first]){
for(int& j:mp_front[it.first]){
if(i==j){//避免是同一个字符串的情形
continue;
}
st.insert(phrases[i]+phrases[j].substr(it.first.size()));
}
}
}
}
return vector<string>(st.begin(),st.end());//返回结果
}
};