解法一

模拟。每次的候选单词都是上一次的子集。

  1. import java.util.*;
  2. class Solution {
  3. public List<List<String>> suggestedProducts(String[] products, String searchWord) {
  4. List<List<String>> ans = new ArrayList<>(searchWord.length());
  5. List<String> last = new ArrayList<>(searchWord.length());
  6. for (String str : products) {
  7. if (str.charAt(0) == searchWord.charAt(0)) {
  8. last.add(str);
  9. }
  10. }
  11. Comparator<String> stringComparator = new Comparator<String>() {
  12. @Override
  13. public int compare(String o1, String o2) {
  14. return o1.compareTo(o2);
  15. }
  16. };
  17. last.sort(stringComparator);
  18. if (last.size() > 3) {
  19. ans.add(last.subList(0, 3));
  20. } else {
  21. ans.add(last);
  22. }
  23. for (int i = 1; i < searchWord.length(); ++i) {
  24. String prefix = searchWord.substring(0, i + 1);
  25. List<String> current = new ArrayList<>(last.size());
  26. Iterator<String> iterator = last.listIterator();
  27. while (iterator.hasNext()) {
  28. String str = iterator.next();
  29. if (str.startsWith(prefix)) {
  30. current.add(str);
  31. }
  32. }
  33. if (current.size() > 3) {
  34. ans.add(current.subList(0, 3));
  35. } else {
  36. ans.add(current);
  37. }
  38. last = current;
  39. }
  40. return ans;
  41. }
  42. }