LeetCode题目:1268. 搜索推荐系统

题目

题目链接:https://leetcode-cn.com/problems/search-suggestions-system/
题目解析:
给你一个搜索字符串数组,再给你一个搜索字符串,搜索字符串从第一个字符,前两个字符,前三个字符,依次组成的字符串去搜索字符串数组中相同的字符串,并按照字典顺序输出前三个字符串。

  1. 用Collection集合的sort方法将字符串数组按照字典排序排列好
  2. 搜索字符串进行遍历
  3. 取下前几个字符组成字符串
  4. 再跟字符串数组进行遍历搜索
  5. 将搜索到的字符串放入集合中
  6. 再将集合放入大集合中

代码

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);
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值