#include #include #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; list ok; bool match; list ::iterator oit, noit; int i, j, k; sort (products.begin(), products.end()); rv.resize(sw.size()); for (i = 0; i < products.size(); i++) { ok.push_back(-i); // Yes, I put negative indices in here. } for (i = 0; i < sw.size(); i++) { // You'll note, I quit when rv[i].size() gets to three. // That's why I have the negative indices for (oit = ok.begin(); oit != ok.end() && rv[i].size() < 3; oit = noit) { noit = oit; // This allows me to delete oit easily and not noit++; // mess up the for loop. j = *oit; if (j < 0) { // If the index is negative, it means I haven't seen this j = -j; // word before, so I need to make sure the first i characters match. *oit = j; // Then I set the index to positive. Sorry -- it's confusing. match = (products[j].size() > i); for (k = 0; match && k < i; k++) match = (products[j][k] == sw[k]); } else { match = true; } // printf("i:%d p[j]:%s m:%d\n", i, products[j].c_str(), (match) ? 1 : 0); if (!match || products[j].size() < (i+1) || products[j][i] != sw[i]) { ok.erase(oit); } else { rv[i].push_back(products[j]); } } } return 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; }