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:

  1. The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
  2. 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).
  3. If less than 3 hot sentences exist, then just return as many as you can.
  4. 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的更多相关文章

  1. [LeetCode] Design Search Autocomplete System 设计搜索自动补全系统

    Design a search autocomplete system for a search engine. Users may input a sentence (at least one wo ...

  2. [LeetCode] 642. Design Search Autocomplete System 设计搜索自动补全系统

    Design a search autocomplete system for a search engine. Users may input a sentence (at least one wo ...

  3. [LeetCode] Design Log Storage System 设计日志存储系统

    You are given several logs that each log contains a unique id and timestamp. Timestamp is a string t ...

  4. 【leetcode】1268. Search Suggestions System

    题目如下: Given an array of strings products and a string searchWord. We want to design a system that su ...

  5. [LeetCode] Design In-Memory File System 设计内存文件系统

    Design an in-memory file system to simulate the following functions: ls: Given a path in string form ...

  6. 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 ...

  7. LeetCode Design Log Storage System

    原题链接在这里:https://leetcode.com/problems/design-log-storage-system/description/ 题目: You are given sever ...

  8. Binary search tree system and method

    A binary search tree is provided for efficiently organizing values for a set of items, even when val ...

  9. Design In-Memory File System

    Design an in-memory file system to simulate the following functions: ls: Given a path in string form ...

随机推荐

  1. [PWN]fsb with stack frame

    0x00: 格式化字符串漏洞出现的时间很早了,偶然在前一段时间学到了一个其他的利用姿势,通过栈桢结构去利用格式化字符串漏洞. 原文链接:http://phrack.org/issues/59/7.ht ...

  2. java 项目 文件关系 扫描 注释注入(3)

    @RequestParam和@PathVariable用法小结  https://www.cnblogs.com/helloworld-hyyx/p/5295514.html(copy) @Reque ...

  3. JavaWeb-SpringBoot_(上)腾讯云点播服务之视频的上传-demo

    使用Gradle编译项目 传送门 腾讯视频云点播 传送门 项目已托管到Github上 传送门 腾讯云点播服务之视频的显示(下) 传送门 个人腾讯云控制台中的视频管理 IndexController.j ...

  4. conda程序使用

    conda -c 参数 使用清华镜像时不要使用-c 参数.-c参数是anaconda的默认channel. 查询安装源中某个包的可以安装的版本 conda search -f package_name ...

  5. 学号 20175329 《Java程序设计》第10周学习总结

    20175329 <Java程序设计>第十周学习总结 教材学习内容总结 线程与进程 进程时程序的一次动态执行过程.线程是比进程更小的执行单位,一个进程在其执行过程中,可以产生多个线程. J ...

  6. Mac平台最好用的万能开源免费播放器-IINA

    1.安装 1)官网下载地址 https://iina.io/ 2)brew 方式安装 testdeMacBook-Pro:~ test$ brew cask install iina Updating ...

  7. 石川es6课程---9、面向对象-基础

    石川es6课程---9.面向对象-基础 一.总结 一句话总结: js老版本的面向对象和继承都不是很方便,新版的面向对象向其它语言靠拢,有了class,extends,constructor等关键字,用 ...

  8. Omnigraffle

    OmniGraffle 7 Mac 注册码 账号:Appked 密码:MFWG-GHEB-HYTW-CGHT-CSXU-QCNC-SXU https://blog.csdn.net/ChibiMaru ...

  9. BitmapRegionDecoder

    Android加载大图——BitmapRegionDecoder(转)   BitmapRegionDecoder,从API10就引入了.如下图:   NPONRY0T35GE$13{254X8Z1. ...

  10. Android jni/ndk编程一:jni初级认识与实战体验

    Android平台很多地方都可以看到jni的身影,比如之前接触到一个投屏的项目,主要的代码是c/c++写的,然后通过Jni供Java层调用;另外,就拿Android系统中的Service来说,很多的S ...