收到一只叮咚
这种方法应该有效。#include <bits/stdc++.h>using namespace std;vector<set<int>> getres(vector<string> sentences, vector<string> phrases, vector<set<int>> v){map<string,set<int>> m;map<string,set<int>> :: iterator itr;for(int i=0;i<sentences.size();i++){ string temp = sentences[i]; temp.push_back(' '); string word = ""; for(int j=0;j<temp.length();j++){ if(temp[j] == ' '){ itr = m.find(word); if(itr == m.end()){ set<int> s; s.insert(i); m.insert({word,s}); } else if(itr != m.end()){ itr->second.insert(i); } word = ""; } else{ word.push_back(temp[j]); } }}// for(itr = m.begin();itr!= m.end();itr++){// cout<<itr->first <<" ";// for(auto f= itr->second.begin();f!= itr->second.end();f++){// cout<<*f<<" ";// }// cout<<endl;// }for(int i=0;i<phrases.size();i++){ string temp = phrases[i]; temp.push_back(' '); string word = ""; int flag = 0; set<int> s1,s2,s3; for(int j=0;j<temp.length();j++){ if(temp[j] == ' '){ // cout<<"yes"; itr = m.find(word); if(itr == m.end()){ flag = 1; break; } else if(itr != m.end()){ if(s1.empty()){ s1 = itr->second; } else{ set_intersection(s1.begin(),s1.end(),itr->second.begin(),itr->second.end(),inserter(s3,s3.begin())); s1 = s3; s3.clear(); if(s1.empty()){ flag = 1; break; } } // for(auto f=s1.begin();f!= s1.end();f++){ // cout<<*f<<" "; // } // cout<<endl; } word = ""; } else{ word.push_back(temp[j]); } } if(flag == 1){ s1.clear(); s1.insert(-1); v[i] = s1; flag = 0 ; } else{ v[i] = s1; } s1.clear(); s2.clear(); s3.clear();}return v;}int main() {vector<string> sentences = {"chris and jennifer had a fight this morning", "chris went on a holiday", "jennifer is in prison"};vector<string> phrases = {"chris jennifer", "jennifer", "prison"};vector<set<int>> v(phrases.size());v = getres(sentences,phrases,v);for(int i=0;i<v.size();i++){ set<int> :: iterator itr; for(itr = v[i].begin() ;itr != v[i].end();itr++){ cout<<*itr<<" "; } cout<<endl;}// cout<<"finish"<<endl;}