当前位置:网站首页>leetcode 1268. Search suggestions system
leetcode 1268. Search suggestions system
2022-06-24 08:43:00 【Blue feather bird】
You are given an array of strings products and a string searchWord.
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 searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.
Return a 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”]
Similar to Baidu , bing Inside , Input a word and the function of recommending relevant terms will appear automatically .
At most, only 3 A word , The candidate entry is products The words inside .
searchWord There will be a maximum of each letter when you type 3 Recommended words .
Ideas :
1.Trie + DFS
Words with this prefix usually think of Trie, The first is to build Trie structure ,
Because when the prefixes are the same, they should be sorted by dictionary order , So after the prefix search, press a~z Search in the order of .
Search with DFS,
Because there are only 26 individual , So each node has 26 Letters .
But this method is complex and time-consuming .
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
Trie trie = new Trie();
List<List<String>> result = new ArrayList<>();
for(String w : products)
trie.insert(w);
String prefix = new String();
for(char c : searchWord.toCharArray()) {
prefix += c;
result.add(trie.getWordsStartingWith(prefix));
}
return result;
}
}
class Trie {
class Node {
boolean isWord = false;
List<Node> children = Arrays.asList(new Node[26]);
};
Node Root, curr;
List<String> resultBuffer;
void dfsWithPrefix(Node curr, String word) {
if(resultBuffer.size() == 3) return;
if(curr.isWord) resultBuffer.add(word);
//prefix The rest is searched alphabetically
for(char c = 'a'; c <= 'z'; c ++) {
if(curr.children.get(c - 'a') != null) {
// With this letter child
dfsWithPrefix(curr.children.get(c - 'a'), word + c); // from child Start searching down
}
}
}
Trie() {
Root = new Node();
}
void insert(String s) {
curr = Root;
for(char c : s.toCharArray()) {
if(curr.children.get(c - 'a') == null)
curr.children.set(c - 'a', new Node());
curr = curr.children.get(c - 'a');
}
curr.isWord = true;
}
List<String> getWordsStartingWith(String prefix) {
curr = Root;
resultBuffer = new ArrayList<String>();
for(char c : prefix.toCharArray()) {
if(curr.children.get(c - 'a') == null) return resultBuffer;
curr = curr.children.get(c - 'a');
}
dfsWithPrefix(curr, prefix);
return resultBuffer;
}
}
2. Double pointer
The premise of double pointer is, of course, to give products Array sorting .
When left The word that points to products[ left ] The length of < searchWord perhaps When the middle letters are inconsistent , explain searchWord Can't be products[left] The prefix of this word ,
At this time left ++,
In the same way products[ right ] The length of < searchWord perhaps When there are inconsistent letters in the middle , explain searchWord Can't be treated as products[ right ] The prefix of this word ,
At this time right --,
When products[left] and products[right] Both contain searchWord As a prefix , Just take it from left to right 3 Just one word , When the number of words in this range <3 when , take left ~ right All words in the range .
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> list = new ArrayList<>();
Arrays.sort(products);
int n = searchWord.length();
int l = 0,r = products.length-1;
for(int i = 0;i<n;i++) {
char ch = searchWord.charAt(i);
while(l <= r && (products[l].length() <= i || products[l].charAt(i) != ch )) {
l++;
}
while(l <= r && (products[r].length() <= i || products[r].charAt(i) != ch )) {
r--;
}
int x = r - l + 1;
ArrayList<String> lis = new ArrayList<>();
for(int j = 0;j<Math.min(x,3);j++) {
lis.add(products[j+l]);
}
list.add(lis);
}
return list;
}
边栏推荐
- Rsync for file backup
- Vscode install the remote -wsl plug-in to connect to the local WSL
- 成为IEEE学生会员
- PHP code encryption + extended decryption practice
- Using ngrok for intranet penetration
- [life thinking] planning and self-discipline
- win11在cmder中使用vim查看内容的时候空白
- 饼状统计图,带有标注线,都可以自行设定其多种参数选项
- Centos7安装jdk8以及mysql5.7以及Navicat连接虚拟机mysql的出错以及解决方法(附mysql下载出错解决办法)
- MySQL 因字符集问题插入中文数据时提示代码 :1366
猜你喜欢

uniapp 热更新后台管理

ZUCC_编译语言原理与编译_实验04 语言与文法

Jenkins自动化部署,连接不到所依赖的服务【已解决】

日本大阪大学万伟伟研究员介绍基于WRS系统机器人的快速集成方法和应用

JUC个人简单笔记

5 minutes, excellent customer service chat handling skills
![Fundamentals of 3D mathematics [17] inverse square theorem](/img/59/bef931d96883288766fc94e38e0ace.png)
Fundamentals of 3D mathematics [17] inverse square theorem

【团队管理】测试团队绩效管理的25点小建议

ZUCC_编译语言原理与编译_实验08 语法分析 LR 分析

分布式 | 如何与 DBLE 进行“秘密通话”
随机推荐
Promise usage scenarios
Fund raising, trading and registration
ZUCC_编译语言原理与编译_实验05 正则表达式、有限自动机、词法分析
JUC personal simple notes
Opencv实现图像的基本变换
2021-06-24: find the length of the longest non repeating character substring in a string.
AUTO PWN
QPS, TPS, concurrent users, throughput relationship
Two methods of QT exporting PDF files
QTimer定时器不起作用的原因
数据库,查询本月借出书的数量,如果高于10本时,显示“本月借出书大于10本”,否则显示“本月借出书小于10本”
常用日期格式符与Qt获取当前时间的办法
OpenCV to realize the basic transformation of image
How to handle the problem that calling easycvr address integration cannot be played through easyplayer player?
定时备份数据库脚本
Ordinary token
Using ngrok for intranet penetration
Permission model DAC ACL RBAC ABAC
uniapp 热更新后台管理
MySQL 因字符集问题插入中文数据时提示代码 :1366