Design Search Autocomplete System
Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except '#', you need to return the top 3historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:
- The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
- The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).
- If less than 3 hot sentences exist, then just return as many as you can.
- When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.
Your job is to implement the following functions:
The constructor function:
AutocompleteSystem(String[] sentences, int[] times): This is the constructor. The input is historical data. Sentences is a string array consists of previously typed sentences. Times is the corresponding times a sentence has been typed. Your system should record these historical data.
Now, the user wants to input a new sentence. The following function will provide the next character the user types:
List<String> input(char c): The input c is the next character typed by the user. The character will only be lower-case letters ('a' to 'z'), blank space (' ') or a special character ('#'). Also, the previously typed sentence should be recorded in your system. The output will be the top 3 historical hot sentences that have prefix the same as the part of sentence already typed.
Example:
Operation: AutocompleteSystem(["i love you", "island","ironman", "i love leetcode"], [5,3,2,2])
The system have already tracked down the following sentences and their corresponding times: "i love you" : 5 times "island" : 3 times "ironman" : 2 times "i love leetcode" : 2 times
Now, the user begins another search:
Operation: input('i')
Output: ["i love you", "island","i love leetcode"]
Explanation:
There are four sentences that have prefix "i". Among them, "ironman" and "i love leetcode" have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, "i love leetcode" should be in front of "ironman". Also we only need to output top 3 hot sentences, so "ironman" will be ignored.
Operation: input(' ')
Output: ["i love you","i love leetcode"]
Explanation:
There are only two sentences that have prefix "i ".
Operation: input('a')
Output: []
Explanation:
There are no sentences that have prefix "i a".
Operation: input('#')
Output: []
Explanation:
The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.
class AutocompleteSystem {
private final Map<String, Integer> cache = new HashMap<String, Integer>();
private String input = "";
public AutocompleteSystem(String[] sentences, int[] times) {
for (int i = ; i < sentences.length; i++) {
cache.put(sentences[i], times[i]);
}
}
public List<String> input(char c) {
if (c == '#') {
Integer count = cache.getOrDefault(input, );
cache.put(input, ++count);
input = "";
return Collections.emptyList();
}
input += c;
return cache.entrySet().stream()
.filter(e -> e.getKey().startsWith(input))
.sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.limit()
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(ArrayList::new));
}
}
class AutocompleteSystem {
class TrieNode {
Map<Character, TrieNode> children;
Map<String, Integer> counts;
boolean isWord;
public TrieNode() {
children = new HashMap<>();
counts = new HashMap<>();
isWord = false;
}
}
TrieNode root;
String prefix;
public AutocompleteSystem(String[] sentences, int[] times) {
root = new TrieNode();
prefix = "";
for (int i = ; i < sentences.length; i++) {
add(sentences[i], times[i]);
}
}
private void add(String s, int count) {
TrieNode cur = root;
for (char c : s.toCharArray()) {
TrieNode next = cur.children.get(c);
if (next == null) {
next = new TrieNode();
cur.children.put(c, next);
}
cur = next;
cur.counts.put(s, cur.counts.getOrDefault(s, ) + count);
}
cur.isWord = true;
}
public List<String> input(char c) {
if (c == '#') {
add(prefix, );
prefix = "";
return new ArrayList<String>();
}
prefix = prefix + c;
TrieNode cur = root;
for (char ch : prefix.toCharArray()) {
TrieNode next = cur.children.get(ch);
if (next == null) {
return new ArrayList<String>();
}
cur = next;
}
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>((a,
b) -> (a.getValue() == b.getValue() ? a.getKey().compareTo(b.getKey()) : b.getValue() - a.getValue()));
for (Map.Entry<String, Integer> entry : cur.counts.entrySet()) {
pq.add(entry);
}
List<String> res = new ArrayList<>();
for (int i = ; i < && !pq.isEmpty(); i++) {
res.add(pq.poll().getKey());
}
return res;
}
}
Design Search Autocomplete System的更多相关文章
- [LeetCode] Design Search Autocomplete System 设计搜索自动补全系统
Design a search autocomplete system for a search engine. Users may input a sentence (at least one wo ...
- [LeetCode] 642. Design Search Autocomplete System 设计搜索自动补全系统
Design a search autocomplete system for a search engine. Users may input a sentence (at least one wo ...
- [LeetCode] Design Log Storage System 设计日志存储系统
You are given several logs that each log contains a unique id and timestamp. Timestamp is a string t ...
- 【leetcode】1268. Search Suggestions System
题目如下: Given an array of strings products and a string searchWord. We want to design a system that su ...
- [LeetCode] Design In-Memory File System 设计内存文件系统
Design an in-memory file system to simulate the following functions: ls: Given a path in string form ...
- How to make a combo box with fulltext search autocomplete support?
I would like a user to be able to type in the second or third word from a TComboBoxitem and for that ...
- LeetCode Design Log Storage System
原题链接在这里:https://leetcode.com/problems/design-log-storage-system/description/ 题目: You are given sever ...
- Binary search tree system and method
A binary search tree is provided for efficiently organizing values for a set of items, even when val ...
- Design In-Memory File System
Design an in-memory file system to simulate the following functions: ls: Given a path in string form ...
随机推荐
- Vue(js框架)
单页技术应用:页面不会跳转,只是局部刷新,利用的是锚点原理. Vue特点:1)组件化 2)数据驱动 Vue的开始使用: 1)先引入Vue文件,引入方式和jquery类似,可以直接引入 <scr ...
- Spring Batch 4.2 新特性
Spring Batch 4.2 的发行版主要增强了下面的改进: 使用 Micrometer 来支持批量指标(batch metrics) 支持从 Apache Kafka topics 读取/写入( ...
- poj 2976 Dropping tests (最大化平均值:二分查找)
#include<iostream> #include<algorithm> #include<stdio.h> #include<math.h> #d ...
- 顺序表应用6:有序顺序表查询(SDUT 3330)
Problem Description 顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在.如果在顺序表中存在该整数,输出其在表中的序号:否则输出&qu ...
- 支持快应用的http网络库-flyio
Fly.js 一个基于Promise的.强大的.支持多种JavaScript运行时的http请求库. 有了它,您可以使用一份http请求代码在浏览器.微信小程序.Weex.Node.React Nat ...
- Selenium定位策略
1.通过XPath使用contains() 它将启动一个窗口,其中包含文本框开发中涉及的所有特定代码. 记下它的id属性. 通过XPath定位元素的语法 - 使用contains()可以写成: //& ...
- flask入门第一篇
一. Python 现阶段三大主流Web框架 Django Tornado Flask 对比 1.Django 主要特点是大而全,集成了很多组件,例如: Models Admin Form 等等, 不 ...
- C++入门经典-例7.10-运算符的重载,重载加号运算符
1:曾经介绍过string类型的数据,它是C++标准模版库提供的一个类.string类支持使用加号“+”连接两个string对象.但是使用两个string对象相减确实非法的,其中的原理就是C++所提供 ...
- python文件夹中pycache文件是什么
python(pycache文件的问题):python属于脚本语言,执行python文件需要通过python解释器将源码转换为字节码,然后供cpu读取,pycache文件夹里面保存的就是py文件对应的 ...
- PHP冒泡排序原生代码
//冒泡排序 $arr=array(23,5,26,4,9,85,10,2,55,44,21,39,11,16,55,88,421,226,588); $n =count($arr); //echo ...