Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Runtime: 50 ms, faster than 72.32% of Java online submissions for Palindrome Pairs.
- // Memory Usage: 50.9 MB, less than 21.95% of Java online submissions for Palindrome Pairs.
- class Solution {
- public List<List<Integer>> palindromePairs(String[] words) {
- TrieNode trie = new TrieNode();
- for (int i = 0; i < words.length; i++) trie.add(words[i], i);
- List<List<Integer>> result = new ArrayList<List<Integer>>();
- for (int i = 0; i < words.length; i++) {
- String word = words[i];
- TrieNode node = trie;
- for (int j = word.length() - 1; j >= 0 && node != null; j--) {
- char c = word.charAt(j);
- TrieNode next = node.next.get(c);
- if (node.endWord != -1) {
- if (node.endWord != i && isPali(word, 0, j)) {
- result.add(createResult(node.endWord, i));
- }
- }
- node = next;
- }
- if (node != null) {
- for (int wordIndex: node.positions) {
- if (wordIndex == i) continue;
- result.add(createResult(wordIndex, i));
- }
- }
- }
- return result;
- }
- private boolean isPali(String s, int l, int r) {
- while (l < r)
- if (s.charAt(l++) != s.charAt(r--)) return false;
- return true;
- }
- private List<Integer> createResult(int index1, int index2) {
- ArrayList<Integer> r = new ArrayList<>();
- r.add(index1);
- r.add(index2);
- return r;
- }
- class TrieNode {
- public List<Integer> positions;
- public Map<Character, TrieNode> next;
- public int endWord;
- public TrieNode() {
- next = new HashMap<Character, TrieNode>();
- positions = new ArrayList<Integer>();
- endWord = -1;
- }
- public void add(String s, int wordIndex) {
- addInt(s, 0, wordIndex);
- }
- private void addInt(String s, int index, int wordIndex) {
- if (isPali(s, index, s.length() -1)) {
- positions.add(wordIndex);
- }
- if (index >= s.length()) {
- this.endWord = wordIndex;
- return;
- }
- char c = s.charAt(index);
- TrieNode n = getOrAdd(c);
- n.addInt(s, index + 1, wordIndex);
- }
- private TrieNode getOrAdd(char c) {
- TrieNode n = next.get(c);
- if (n == null) {
- n = new TrieNode();
- next.put(c, n);
- }
- return n;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement