|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class _1268 { |
| 7 | + public static class Solution1 { |
| 8 | + public List<List<String>> suggestedProducts(String[] products, String searchWord) { |
| 9 | + TrieNode root = buildTrie(products); |
| 10 | + List<List<String>> result = new ArrayList<>(); |
| 11 | + for (int i = 1; i <= searchWord.length(); i++) { |
| 12 | + String searchTerm = searchWord.substring(0, i); |
| 13 | + result.add(findTopThreeMatches(root, searchTerm)); |
| 14 | + } |
| 15 | + return result; |
| 16 | + } |
| 17 | + |
| 18 | + private List<String> findTopThreeMatches(TrieNode root, String searchTerm) { |
| 19 | + List<String> result = new ArrayList<>(); |
| 20 | + TrieNode node = root; |
| 21 | + for (char c : searchTerm.toCharArray()) { |
| 22 | + if (node.children[c - 'a'] == null) { |
| 23 | + return result; |
| 24 | + } else { |
| 25 | + node = node.children[c - 'a']; |
| 26 | + } |
| 27 | + } |
| 28 | + if (node.isWord) { |
| 29 | + result.add(searchTerm); |
| 30 | + } |
| 31 | + for (TrieNode child : node.children) { |
| 32 | + if (child != null) { |
| 33 | + List<String> thisResult = dfs(child, searchTerm, new ArrayList<>()); |
| 34 | + result.addAll(thisResult); |
| 35 | + if (result.size() >= 3) { |
| 36 | + return result.subList(0, 3); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + return result; |
| 41 | + } |
| 42 | + |
| 43 | + private List<String> dfs(TrieNode node, String substring, List<String> result) { |
| 44 | + if (node.isWord) { |
| 45 | + result.add(substring + node.c); |
| 46 | + if (result.size() >= 3) { |
| 47 | + return result; |
| 48 | + } |
| 49 | + } |
| 50 | + for (TrieNode child : node.children) { |
| 51 | + if (child != null) { |
| 52 | + dfs(child, substring + node.c, result); |
| 53 | + } |
| 54 | + } |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | + private TrieNode buildTrie(String[] products) { |
| 59 | + TrieNode root = new TrieNode(' '); |
| 60 | + for (String pro : products) { |
| 61 | + insert(pro, root); |
| 62 | + } |
| 63 | + return root; |
| 64 | + } |
| 65 | + |
| 66 | + private void insert(String word, TrieNode root) { |
| 67 | + TrieNode node = root; |
| 68 | + for (int i = 0; i < word.length(); i++) { |
| 69 | + char c = word.charAt(i); |
| 70 | + if (node.children[c - 'a'] == null) { |
| 71 | + node.children[c - 'a'] = new TrieNode(c); |
| 72 | + } |
| 73 | + node = node.children[c - 'a']; |
| 74 | + } |
| 75 | + node.isWord = true; |
| 76 | + } |
| 77 | + |
| 78 | + class TrieNode { |
| 79 | + TrieNode[] children = new TrieNode[26]; |
| 80 | + boolean isWord; |
| 81 | + char c; |
| 82 | + |
| 83 | + public TrieNode(char c) { |
| 84 | + this.c = c; |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments