class Solution { public: string gethead(string str){//获取头单词 string ret = ""; int strlen = str.length(); for(int i = 0; i < strlen; ++i){ if(str[i] == ' '){ break; } ret += str[i]; } return ret; } string gettail(string str){//获取尾单词 int strlen = str.length(); int index = 0; for(int i = strlen - 1; i >= 0; i--){ if(str[i] == ' '){ index = i; break; } } if(index == 0){ return str; } return str.substr(index+1,strlen);; } string deletesubstr(string str,string substr){//删除重复的单词【为了拼接】;只能删除第一个单词,不能删除最后一个单词【与空格有关】 string strT = str; int pos = strT.find(substr); if (pos >-1) { strT.erase(pos,substr.size()); } return strT; } vector<string> beforeAndAfterPuzzles(vector<string>& phrases) { int phraseslen = phrases.size(); vector<string> head; vector<string> tail; for(int i = 0; i < phraseslen; ++i){//获取头尾词的数组 head.push_back(gethead(phrases[i])); tail.push_back(gettail(phrases[i])); } vector<string> ret; for(int j = 0; j < phraseslen; ++j){//尾部 for(int k = 0; k < phraseslen; ++k){ if(j != k && tail[j] == head[k]){//如果某个子串的头等于另一个子串的尾 ret.push_back(phrases[j] + deletesubstr(phrases[k],head[k]));//把他拼接起来放在返回容器中 cout << phrases[j] + deletesubstr(phrases[k],head[k]) << endl; } } } sort(ret.begin(), ret.end()); ret.erase(unique(ret.begin(), ret.end()), ret.end());//去重 return ret; } };