题目如下:

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"
Output: [
["mobile","moneypot","monitor"],
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"],
["mouse","mousepad"]
]
Explanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]

Example 2:

Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]

Example 3:

Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]

Example 4:

Input: products = ["havana"], searchWord = "tatiana"
Output: [[],[],[],[],[],[],[]]

Constraints:

  • 1 <= products.length <= 1000
  • 1 <= Σ products[i].length <= 2 * 10^4
  • All characters of products[i] are lower-case English letters.
  • 1 <= searchWord.length <= 1000
  • All characters of searchWord are lower-case English letters.

解题思路:首先对products排序,接下来把每个product存入字典树中,字典树每个节点除了保存子节点的地址之外,还存前三个前缀能映射到该节点的product。

代码如下:

class TreeNode(object):
def __init__(self,val):
self.val = val
self.child = {}
self.top3 = []
class Trie(object):
def __init__(self):
self.root = TreeNode(None)
def add(self,word):
node = self.root
for i in word:
if i not in node.child:
child_node = TreeNode(i)
node.child[i] = child_node
if len(node.top3) < 3:
node.top3.append(word)
node = node.child[i]
if len(node.top3) < 3:
node.top3.append(word) def search(self,prefix):
node = self.root
for i in prefix:
if i not in node.child:
return []
node = node.child[i]
return node.top3 class Solution(object):
def suggestedProducts(self, products, searchWord):
"""
:type products: List[str]
:type searchWord: str
:rtype: List[List[str]]
"""
products.sort()
trie = Trie()
for product in products:
trie.add(product)
res = []
word = ''
for char in searchWord:
word += char
res.append(trie.search(word)) return res

【leetcode】1268. Search Suggestions System的更多相关文章

  1. 【LeetCode】74. Search a 2D Matrix

    Difficulty:medium  More:[目录]LeetCode Java实现 Description Write an efficient algorithm that searches f ...

  2. 【LeetCode】1166. Design File System 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 目录树 日期 题目地址https://leetc ...

  3. 【LeetCode】81. Search in Rotated Sorted Array II 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/search-in ...

  4. 【LeetCode】240. Search a 2D Matrix II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  5. 【LeetCode】74. Search a 2D Matrix 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 左下或者右上开始查找 顺序查找 库函数 日期 题目地 ...

  6. 【LeetCode】33. Search in Rotated Sorted Array 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...

  7. 【LeetCode】700. Search in a Binary Search Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...

  8. 【leetcode】Word Search

    Word Search Given a 2D board and a word, find if the word exists in the grid. The word can be constr ...

  9. 【leetcode】Binary Search Tree Iterator(middle)

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

随机推荐

  1. nginx反向代理集群配置

    #user nobody;worker_processes 1; #error_log logs/error.log;#error_log logs/error.log notice;#error_l ...

  2. Oracle密码过期(the password has expired)

    1.进入sqlplus模式--sqlplus / as sysdba; 2.查看用户密码的有效期设置(一般默认的配置文件是DEFAULT) SELECT * FROM dba_profiles WHE ...

  3. AssertionError [ERR_ASSERTION]: Task function must be specified,gulp版本不一致

    报错信息: vue项目打包报错 > innovate-admin-vue@ build /home/soldier/SOLDIER/IDE_project/webStorm_project/in ...

  4. python中argparse模块简单使用

    python中argparse模块简单使用 简介 argparse是python用于解析命令行参数和选项的标准模块.argparse模块的作用是用于解析命令行参数. 使用步骤 1.首先导入该模块 2. ...

  5. SSM @Autowired注入失败

    1, Intellij IDEA中Mybatis Mapper自动注入警告的6种解决方案 https://blog.csdn.net/weixin_30945319/article/details/9 ...

  6. mysql转换表的存储引擎方法

    如果转换表的存储引擎,将会丢失原存储引擎的所有特性. 例如:如果将innodb转换成myisam,再转回innodb,原innodb表的的外键将丢失. 假设默认存储引擎是MyISAM转为InnoDB ...

  7. debezium关于cdc的使用(上)

    博文原址:debezium关于cdc的使用(上) 简介 debezium是一个为了捕获数据变更(cdc)的开源的分布式平台.启动并指向数据库,当其他应用对此数据库执行inserts.updates.d ...

  8. js 获取当前月份 第一天和最后一天

    js 获取当前月份 第一天和最后一天 var now = new Date(); //当前日期 var nowMonth = now.getMonth(); //当前月 var nowYear = n ...

  9. js 发送异步请求

    js用XMLHttpRequest发送异步请求 发送GET请求 var xhr = new XMLHttpRequest(); xhr.open('GET',url);//url为请求地址 xhr.r ...

  10. IOS手机伪类a:active失效

    IOS手机伪类a:active失效:点击更改颜色,松开恢复 解决方案:OS系统的移动设备中,需要在按钮元素或body/html上绑定一个touchstart事件才能激活:active状态 docume ...