Advertisement
El_GEMMY

search suggestions system

Jun 19th, 2022
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) {
  4.         map<string, vector<string>> list;
  5.        
  6.         for(auto& word : products){
  7.             string prefix;
  8.             for(auto& letter : word){
  9.                 prefix += letter;
  10.                 list[prefix].emplace_back(word);
  11.             }
  12.         }
  13.        
  14.        
  15.         vector<vector<string>> ans;
  16.         string prefix;
  17.         for(auto& letter : searchWord){
  18.             prefix += letter;
  19.             auto& curr = list[prefix];
  20.            
  21.             sort(curr.begin(), curr.end());
  22.            
  23.             vector<string> tmp;
  24.             for(int i = 0; i < min(3, (int)curr.size()); i++){
  25.                 tmp.emplace_back(curr[i]);
  26.             }
  27.             ans.emplace_back(tmp);
  28.         }
  29.        
  30.         return ans;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement