在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of strings products and a string searchWord. We want to design a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products. Return list of lists of the suggested products after each character of searchWord is typed. Example 1: Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" Input: products = ["havana"], searchWord = "havana" Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags" Input: products = ["havana"], searchWord = "tatiana" Constraints: 1 <= products.length <= 1000 给你一个产品数组 products 和一个字符串 searchWord ,products 数组中每个产品都是一个字符串。 请你设计一个推荐系统,在依次输入单词 searchWord 的每一个字母后,推荐 products 数组中前缀与 searchWord 相同的最多三个产品。如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个。 请你以二维列表的形式,返回在输入 searchWord 每个字母后相应的推荐产品的列表。 示例 1: 输入:products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse" 输入:products = ["havana"], searchWord = "havana" 输入:products = ["bags","baggage","banner","box","cloths"], searchWord = "bags" 输入:products = ["havana"], searchWord = "tatiana" 提示: 1 <= products.length <= 1000 Runtime: 444 ms
Memory Usage: 24 MB
1 class Solution { 2 func suggestedProducts(_ products: [String], _ searchWord: String) -> [[String]] { 3 let products = products.sorted(by:<) 4 var res:[[String]] = [[String]]() 5 var sb:String = String() 6 let cs:[Character] = Array(searchWord) 7 var idx:Int = 0 8 for c in cs 9 { 10 sb.append(c) 11 let curSearch = sb 12 var cur:[String] = [String]() 13 if idx >= products.count 14 { 15 res.append(cur) 16 continue 17 } 18 while (idx < products.count && products[idx] < curSearch) 19 { 20 idx += 1 21 } 22 var idxCopy:Int = idx 23 for _ in 0..<3 24 { 25 if idxCopy >= products.count 26 { 27 break 28 } 29 if products[idxCopy].hasPrefix(curSearch) 30 { 31 cur.append(products[idxCopy]) 32 idxCopy += 1 33 } 34 else 35 { 36 break 37 } 38 } 39 res.append(cur) 40 } 41 return res 42 } 43 }
|
请发表评论