#include #include #include #include #include using namespace std; class Solution { public: vector> suggestedProducts(vector& products, string searchWord); }; vector> Solution::suggestedProducts(vector& products, string sw) { vector < vector > rv; // My return value vector < string > l; // Subarray to build the return value set w; // Set of all words in products string prefix; // The prefix of the search word. set ::iterator wit; size_t i; int j; /* Create the set. */ for (i = 0; i < products.size(); i++) w.insert(products[i]); /* Iterate through every prefix of the search word. */ for (i = 1; i <= sw.size(); i++) { prefix = sw.substr(0, i); // Set the prefix wit = w.lower_bound(prefix); // Find the smallest word in the set // greater than or equal to the prefix l.clear(); // Put words on the rv as long as theh prefix matches for (j = 0; j < 3 && wit != w.end() && wit->substr(0, i) == prefix; j++) { l.push_back(*wit); wit++; } rv.push_back(l); } return rv; } /* Here's a main that reads the products and then the search word and prints the rv. */ int main() { string w; vector p; string sw; vector < vector > rv; Solution s; size_t i, j; while (cin >> w) p.push_back(w); sw = w; p.pop_back(); rv = s.suggestedProducts(p, sw); for (i = 0; i < rv.size(); i++) { for (j = 0; j < rv[i].size(); j++) { cout << " " << rv[i][j]; } cout << endl; } return 0; }