地址 https://leetcode-cn.com/problems/search-suggestions-system/算法
題目描述
給你一個產品數組 products 和一個字符串 searchWord ,products 數組中每一個產品都是一個字符串。數組
請你設計一個推薦系統,在依次輸入單詞 searchWord 的每個字母后,推薦 products 數組中前綴與 searchWord 相同的最多三個產品。若是前綴相同的可推薦產品超過三個,請按字典序返回最小的三個。spa
請你以二維列表的形式,返回在輸入 searchWord 每一個字母后相應的推薦產品的列表。設計
樣例code
示例 1: 輸入:products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" 輸出:[ ["mobile","moneypot","monitor"], ["mobile","moneypot","monitor"], ["mouse","mousepad"], ["mouse","mousepad"], ["mouse","mousepad"] ] 解釋:按字典序排序後的產品列表是 ["mobile","moneypot","monitor","mouse","mousepad"] 輸入 m 和 mo,因爲全部產品的前綴都相同,因此係統返回字典序最小的三個產品 ["mobile","moneypot","monitor"] 輸入 mou, mous 和 mouse 後系統都返回 ["mouse","mousepad"] 示例 2: 輸入:products = ["havana"], searchWord = "havana" 輸出:[["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]] 示例 3: 輸入:products = ["bags","baggage","banner","box","cloths"], searchWord = "bags" 輸出:[["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]] 示例 4: 輸入:products = ["havana"], searchWord = "tatiana" 輸出:[[],[],[],[],[],[],[]] 提示: 1 <= products.length <= 1000 1 <= Σ products[i].length <= 2 * 10^4 products[i] 中全部的字符都是小寫英文字母。 1 <= searchWord.length <= 1000 searchWord 中全部字符都是小寫英文字母。
算法1
據大佬們說 有什麼前綴樹的解答
我想了想用trie樹的方案 沒結果
就開始硬懟了。
首先在products 按照字典序排序,而後另開數組記錄對應的單詞 與 搜索單詞相同的字母數blog
再遍歷這個記錄相同字母數的數組 找到相同一個單字的詞彙 找到相同兩個單字的詞彙。。。。。。
遍歷或者找到或者找不到爲空, 中途剪枝爲若是找到符合要求的3個詞彙也提早退出(因爲已經按照字典序排序,最開始找到的符合要求的3個詞彙確定是字典序優先的)排序
C++ 代碼leetcode
class Solution { public: vector<vector<string>> ret; int GetsameCharCount(const string& target,const string& src){ int ret =0; for(int i=0;i < target.size() && i < src.size();i++ ){ if(target[i] == src[i]) ret++; else{ break; } } return ret; } vector<vector<string>> suggestedProducts(vector<string>& products, string searchWord) { sort(products.begin(),products.end()); vector<int> sameCharCount; for(int i = 0; i < products.size();i++){ int t = GetsameCharCount(products[i],searchWord); sameCharCount.push_back(t); } for(int i = 0; i < searchWord.size();i++){ vector<string> v; for(int j = 0; j < sameCharCount.size();j++){ if(sameCharCount[j] >i){ v.push_back(products[j]); } if(v.size() == 3) break; } ret.push_back(v); } return ret; } };