1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| class Solution { private static class TrieNode { private final TrieNode[] children; private String word;
public TrieNode() { this.children = new TrieNode[26]; } }
private static class Trie { private final TrieNode root;
public Trie() { this.root = new TrieNode(); }
public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if (node.children[index] == null) { node.children[index] = new TrieNode(); } node = node.children[index]; } node.word = word; }
public List<String> search(String big) { List<String> wordList = new ArrayList<>(); TrieNode node = root; for (int i = 0; i < big.length(); i++) { int index = big.charAt(i) - 'a'; node = node.children[index]; if (node == null) { break; } if (node.word != null) { wordList.add(node.word); } }
return wordList; } }
public int[][] multiSearch(String big, String[] smalls) { Trie trie = new Trie(); for (String word : smalls) { trie.insert(word); }
Map<String, List<Integer>> wordToStartIndexMap = new HashMap<>(); for (int startIndex = 0; startIndex < big.length(); startIndex++) { for (String word : trie.search(big.substring(startIndex))) { wordToStartIndexMap.computeIfAbsent(word, k -> new ArrayList<>()).add(startIndex); } }
int[][] res = new int[smalls.length][]; for (int i = 0; i < smalls.length; i++) { List<Integer> startIndexList = wordToStartIndexMap.getOrDefault(smalls[i], Collections.emptyList()); res[i] = new int[startIndexList.size()]; for (int j = 0; j < startIndexList.size(); j++) { res[i][j] = startIndexList.get(j); } } return res; } }
|