Search Suggestions System
给一个字符串数组, 里面是products, 给一个searchword, 求写一个推荐系统. 这个用treeset来做, 注意两个特殊情况, 一个是第一位就不匹配的时候, 就别推荐了… 一个是treeset的highkey和lowkey不能判断字符串的匹配, 他们只是判断字典序的顺序, 需要多加一句匹配判断.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Solution { public List<List<String>> suggestedProducts(String[] products, String searchWord) { TreeSet<String> set = new TreeSet<>(); List<List<String>> res = new ArrayList<>(); for(String p : products) if (p.charAt(0) == searchWord.charAt(0)) set.add(p); for(int i = 0 ; i < searchWord.length(); i++) { String w = searchWord.substring(0,i+1); List<String> tmp = new ArrayList<>(); for (int j = 0; j < 3; j++) { String str = set.ceiling(w); if (!set.isEmpty() && str != null && str.contains(w)) { tmp.add(str); set.remove(str); } } set.addAll(tmp); res.add(tmp); } return res; } } |