euisblue
1268. Search Suggestions System

C++

1class Solution { 2 public: 3 vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) { 4 sort(products.begin(), products.end()); 5 vector<vector<string> > answer; 6 bool wasIt = false; 7 8 int i=0; 9 for(char ch : searchWord) { 10 vector<string> temp, re; 11 12 for(string str : products) { 13 if(str.size() <= i) continue; 14 if(str[i] == ch) { 15 temp.push_back(str); 16 } 17 } 18 19 for(int j=0; j<3 && j<temp.size(); ++j) 20 re.push_back(temp[j]); 21 22 answer.push_back(re); 23 products = temp; 24 ++i; 25 } 26 27 return answer; 28 } 29};