里程商城为了方便客户更快速查找到所需商品,希望实现一个根据用户输入,前缀匹配商品名的功能,用户可能输入多个关键词,则每个关键词分别进行匹配,分别输出结果。现给定商品名称数组、用户输入的关键词数组,输出每个关键词的匹配结果。(待查询的商品信息可能非常多) 示例1 输入:["huawei phone","huawei router","apple iphone","xiaomi mix"],["huawei","apple"] 返回值:[["huawei phone","huawei router"],["apple iphone"]] 用Java代码实现
时间: 2023-02-08 14:59:56 浏览: 68
可以使用 Java 中的 HashMap 来实现这个功能。
首先将每个关键词作为 key,对应的匹配结果数组作为 value 存入 HashMap 中。
然后遍历商品名称数组,对于每个商品名称,遍历关键词数组,判断商品名称是否以每个关键词为前缀,如果是,则将商品名称添加到对应关键词的匹配结果数组中。
最后将 HashMap 中的所有 value 取出来,即为每个关键词的匹配结果。
代码如下:
```java
import java.util.HashMap;
import java.util.ArrayList;
public class Matching {
public static ArrayList<ArrayList<String>> match(String[] products, String[] keywords) {
HashMap<String, ArrayList<String>> map = new HashMap<>();
for (String keyword : keywords) {
map.put(keyword, new ArrayList<String>());
}
for (String product : products) {
for (String keyword : keywords) {
if (product.startsWith(keyword)) {
map.get(keyword).add(product);
}
}
}
return new ArrayList<ArrayList<String>>(map.values());
}
public static void main(String[] args) {
String[] products = {"huawei phone","huawei router","apple iphone","xiaomi mix"};
String[] keywords = {"huawei","apple"};
ArrayList<ArrayList<String>> res = match(products, keywords);
System.out.println(res);
}
}
```
运行结果为:[[huawei phone, huawei router], [apple iphone]]
该算法的时间复杂度为O(n * m),其中n为商品名称数组的长度,m为关键词数组的长度。