力扣刷题总结

1.【搜索推荐系统】

https://leetcode-cn.com/problems/search-suggestions-system/

给你一个产品数组 products 和一个字符串 searchWord ,products 数组中每个产品都是一个字符串。

请你设计一个推荐系统,在依次输入单词 searchWord 的每一个字母后,推荐 products 数组中前缀与 searchWord 相同的最多三个产品。如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个。

请你以二维列表的形式,返回在输入 searchWord 每个字母后相应的推荐产品的列表。

思想:主要是数组要先进行排序Arrays.sort(products) 然后再暴力破解

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RecommendSystem {
    public static void main(String[] args) {
        String[] products = {"bags", "baggage", "banner", "box", "cloths"};
        String searchWord = "bags";
        suggestedProducts(products, searchWord);

    }

    public static List<List<String>> suggestedProducts(String[] products, String searchWord) {
        Arrays.sort(products);
        List<List<String>> resultList = new ArrayList<>();

        for (int i = 0; i < searchWord.length(); i++) {
            List<String> eachResultList = new ArrayList<>();
            String tempStr = searchWord.substring(0, i + 1);
            int count = 0;
            for (int j = 0; j < products.length; j++) {
                if (products[j].length() >= (i + 1)) {
                    String productStrTemp = products[j].substring(0, i + 1);
                    if (productStrTemp.equals(tempStr)) {
                        count++;
                        eachResultList.add(products[j]);
                        if (count == 3) {
                            break;
                        }
                    }
                }
            }
            resultList.add(eachResultList);
        }
        return resultList;
    }
}

猜你喜欢

转载自www.cnblogs.com/zdjBlog/p/12622674.html
今日推荐