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 ...
随机推荐
- ssh2整合: No bean named 'sessionFactory' is defined(求大神指点)
applicationContext.xml 中已经配置 <bean id="sessionFactory" class="org.springframework. ...
- cookbook 11.1 在文本控制台中显示进度条
任务: 在进行长时间操作时,向用户显示一个"进度指示条". 解决方案: #coding=utf-8 import sys class progressbar(object): de ...
- 去除弹窗自带url提示
window.alert = function(name){ var iframe = document.createElement("IFRAME"); iframe.style ...
- 学习andriod开发之 异步加载图片(二)--- 使用其他进度条
大家好 我是akira上一节 我们讲到使用AsyncTask 这个类进行异步的下载 主要是涉及到一些图片的更新 这次我们继续上一个demo的改进 . 不知道你是否发现一个问题 上一节我们遗留了两个bu ...
- Linux网络编程三、 IO操作
当从一个文件描述符进行读写操作时,accept.read.write这些函数会阻塞I/O.在这种会阻塞I/O的操作好处是不会占用cpu宝贵的时间片,但是如果需要对多个描述符操作时,阻塞会使同一时刻只能 ...
- Inter IPP 处理图像数据的方法
Inter IPP没有读取图片和保存图片的函数,需要结合opencv完成这个功能. opencv读到图片以后逐个像素点赋值给IPP显然是不可取的,方法如下: int main(int argc, ch ...
- vue 使用axios 出现跨域请求的两种解决方法
最近在使用vue axios发送请求,结果出现跨域问题,网上查了好多,发现有好几种结局方案. 1:服务器端设置跨域 header(“Access-Control-Allow-Origin:*”); h ...
- Riot.js——一个小而美的JS框架
Riot.js是什么? Riot 拥有创建现代客户端应用的所有必需的成分: "响应式" 视图层用来创建用户界面 用来在各独立模块之间进行通信的事件库 用来管理URL和浏览器回退按钮 ...
- leetcode题目15.三数之和(中等)
题目描述: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重 ...
- TCP输入 之 tcp_v4_rcv
tcp_v4_rcv函数为TCP的总入口,数据包从IP层传递上来,进入该函数:其协议操作函数结构如下所示,其中handler即为IP层向TCP传递数据包的回调函数,设置为tcp_v4_rcv: sta ...