# Hard-题目47：336. Palindrome Pairs

Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Given words = [“bat”, “tab”, “cat”]
Return [[0, 1], [1, 0]]
The palindromes are [“battab”, “tabbat”]
Example 2:
Given words = [“abcd”, “dcba”, “lls”, “s”, “sssll”]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are [“dcbaabcd”, “abcddcba”, “slls”, “llssssll”]

int index，如果该点是单词，则记录在原列表的下标，如果不是，该值为-1
List list, 这个列表有点难理解，先摘抄原文如下：
Here I take another strategy: add an integer list to each TrieNode; the list will record the indices of all words satisfying the following two conditions: each word has a suffix represented by the current Trie node; the rest of the word forms a palindrome.

public class Solution {
class TrieNode {
TrieNode[] next;
int index;
List<Integer> list;
TrieNode() {
next = new TrieNode[26];
index = -1;
list = new ArrayList<>();
}
}
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<>();
TrieNode root = new TrieNode();
for (int i = 0; i < words.length; i++)
for (int i = 0; i < words.length; i++)
search(words, i, root, res);
return res;
}
private void addWord(TrieNode root, String word, int index) {
for (int i = word.length() - 1; i >= 0; i--) {
if (root.next[word.charAt(i) - 'a'] == null)
root.next[word.charAt(i) - 'a'] = new TrieNode();
if (isPalindrome(word, 0, i))
root = root.next[word.charAt(i) - 'a'];
}
root.index = index;
}
private void search(String[] words, int i, TrieNode root, List<List<Integer>> list) {
for (int j = 0; j < words[i].length(); j++) {
if (root.index >= 0 && root.index != i && isPalindrome(words[i], j, words[i].length() - 1))
root = root.next[words[i].charAt(j) - 'a'];
if (root == null) return;
}

for (int j : root.list) {
if (i != j)
}
}
private boolean isPalindrome(String word, int i, int j) {
while (i < j) {
if (word.charAt(i++) != word.charAt(j--))
return false;
}
return true;
}
}

63ms
Cmershen的碎碎念：

Leetcode是面向面试的，如果哪位大仙能在面试的短时间和高心理压力下想得到这个算法，真的是大神了……

• 本文已收录于以下专栏：

举报原因： 您举报文章：Hard-题目47：336. Palindrome Pairs 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)