Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. class Solution {
  2. class TrieNode{
  3. boolean isWord = false;
  4. TreeMap <Character, TrieNode> children = new TreeMap();
  5. }
  6.  
  7. class Trie{
  8. TrieNode root = new TrieNode();
  9.  
  10. public void add(String word){
  11. TrieNode curr = root;
  12. for(Character c: word.toCharArray()){
  13. if (!curr.children.containsKey(c)) curr.children.put(c, new TrieNode());
  14. curr = curr.children.get(c);
  15. }
  16. curr.isWord = true;
  17. }
  18.  
  19. public List<String> getWordsWithPrefix(String prefix){
  20. ArrayList<String> ans = new ArrayList();
  21. TrieNode curr = root;
  22. for(Character c: prefix.toCharArray()){
  23. if (curr.children.containsKey(c)) {
  24. curr = curr.children.get(c);
  25. } else return ans;
  26. }
  27. StringBuilder sb = new StringBuilder(prefix);
  28. getWords(sb, curr, ans);
  29. return ans;
  30. }
  31.  
  32. public void getWords(StringBuilder sb,TrieNode curr, ArrayList<String> ans){
  33. if (curr.isWord) {
  34. ans.add(sb.toString());
  35. }
  36. for(Map.Entry<Character, TrieNode> child:curr.children.entrySet()){
  37. if (ans.size() <3) {
  38. sb.append(child.getKey());
  39. getWords(sb, child.getValue(), ans);
  40. sb.deleteCharAt(sb.length()-1);
  41. }
  42. else break;
  43. }
  44. }
  45. }
  46.  
  47. public List<List<String>> suggestedProducts(String[] products, String searchWord) {
  48. Trie trie = new Trie();
  49. for(String product:products){
  50. trie.add(product);
  51. }
  52. List<List<String>> result = new ArrayList();
  53. StringBuilder sb = new StringBuilder();
  54. for(char c:searchWord.toCharArray()){
  55. sb.append(c);
  56. result.add(trie.getWordsWithPrefix(sb.toString()));
  57. }
  58. return result;
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement