|
| 1 | +class Solution { |
| 2 | + //https://leetcode.com/problems/palindrome-pairs/discuss/79195/O(n-*-k2)-java-solution-with-Trie-structure |
| 3 | + private static class TrieNode { |
| 4 | + TrieNode[] next; |
| 5 | + int index; |
| 6 | + List<Integer> list; |
| 7 | + |
| 8 | + TrieNode() { |
| 9 | + next = new TrieNode[26]; |
| 10 | + index = -1; |
| 11 | + list = new ArrayList<>(); |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + public List<List<Integer>> palindromePairs(String[] words) { |
| 16 | + List<List<Integer>> res = new ArrayList<>(); |
| 17 | + |
| 18 | + TrieNode root = new TrieNode(); |
| 19 | + |
| 20 | + for (int i = 0; i < words.length; i++) { |
| 21 | + addWord(root, words[i], i); |
| 22 | + } |
| 23 | + |
| 24 | + for (int i = 0; i < words.length; i++) { |
| 25 | + search(words, i, root, res); |
| 26 | + } |
| 27 | + |
| 28 | + return res; |
| 29 | + } |
| 30 | + |
| 31 | + private void addWord(TrieNode root, String word, int index) { |
| 32 | + for (int i = word.length() - 1; i >= 0; i--) { |
| 33 | + int j = word.charAt(i) - 'a'; |
| 34 | + |
| 35 | + if (root.next[j] == null) { |
| 36 | + root.next[j] = new TrieNode(); |
| 37 | + } |
| 38 | + |
| 39 | + if (isPalindrome(word, 0, i)) { |
| 40 | + root.list.add(index); |
| 41 | + } |
| 42 | + |
| 43 | + root = root.next[j]; |
| 44 | + } |
| 45 | + |
| 46 | + root.list.add(index); |
| 47 | + root.index = index; |
| 48 | + } |
| 49 | + |
| 50 | + private void search(String[] words, int i, TrieNode root, List<List<Integer>> res) { |
| 51 | + for (int j = 0; j < words[i].length(); j++) { |
| 52 | + if (root.index >= 0 && root.index != i && isPalindrome(words[i], j, words[i].length() - 1)) { |
| 53 | + res.add(Arrays.asList(i, root.index)); |
| 54 | + } |
| 55 | + |
| 56 | + root = root.next[words[i].charAt(j) - 'a']; |
| 57 | + if (root == null) return; |
| 58 | + } |
| 59 | + |
| 60 | + for (int j : root.list) { |
| 61 | + if (i == j) continue; |
| 62 | + res.add(Arrays.asList(i, j)); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + private boolean isPalindrome(String word, int i, int j) { |
| 67 | + while (i < j) { |
| 68 | + if (word.charAt(i++) != word.charAt(j--)) return false; |
| 69 | + } |
| 70 | + |
| 71 | + return true; |
| 72 | + } |
| 73 | +} |
0 commit comments