题目
题目链接:https://leetcode-cn.com/problems/search-suggestions-system/
题目解析:
给你一个搜索字符串数组,再给你一个搜索字符串,搜索字符串从第一个字符,前两个字符,前三个字符,依次组成的字符串去搜索字符串数组中相同的字符串,并按照字典顺序输出前三个字符串。
- 用Collection集合的sort方法将字符串数组按照字典排序排列好
- 搜索字符串进行遍历
- 取下前几个字符组成字符串
- 再跟字符串数组进行遍历搜索
- 将搜索到的字符串放入集合中
- 再将集合放入大集合中
代码
class Solution {
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
//调用方法对字符串数组进行字典排序
products = stringsort(products);
//创建一个大的集合用来存放答案
List<List<String>> lists = new ArrayList<List<String>>();
//遍历搜索字符串
for(int i = 0 ;i<searchWord.length();i++) {
//创建字符串变量
String s = "";
//如果i到达最末尾就不切割,否则就切割
if(i==searchWord.length()-1)
{
s = searchWord;
}else {
s = searchWord.substring(0,i+1);
}
//System.out.println(s+": ");
//创建小的集合来存放答案
List<String> list = new ArrayList<>();
//遍历字符串数组
for (String str : products) {
//如果i不是str的末尾字符就切割跟s比是否一样,如果一样就存入list集合中
if(i<=str.length()-1&&str.substring(0,i+1).equals(s)) {
list.add(str);
//System.out.print(str+" ");
//如果i是str末尾字符就不切割直接跟s对比是否一样,如果一样就存入list集合
}else if(i>=str.length()-1&&str.equals(s)) {
list.add(str);
//System.out.print(str+" ");
}
//如果集合中有三个字符串就存满了,跳出循环
if(list.size()==3)
break;
}
//将小的集合放入大的集合中
lists.add(list);
//System.out.println();
}
return lists;
}
//用Collections的sort方法对字符串数组进行字典排序
private static String[] stringsort(String[] products) {
List<String> list = new ArrayList<String>();
for (String str : products) {
list.add(str);
}
Collections.sort(list);
return list.toArray(products);
}
}