# 回文对

<p>给定一组<strong> 互不相同</strong> 的单词， 找出所有<strong> 不同<em> </em></strong>的索引对 <code>(i, j)</code>，使得列表中的两个单词， <code>words[i] + words[j]</code> ，可拼接成回文串。</p>

<p> </p>

<p><strong>示例 1：</strong></p>

<pre>
<strong>输入：</strong>words = ["abcd","dcba","lls","s","sssll"]
<strong>输出：</strong>[[0,1],[1,0],[3,2],[2,4]] 
<strong>解释：</strong>可拼接成的回文串为 <code>["dcbaabcd","abcddcba","slls","llssssll"]</code>
</pre>

<p><strong>示例 2：</strong></p>

<pre>
<strong>输入：</strong>words = ["bat","tab","cat"]
<strong>输出：</strong>[[0,1],[1,0]] 
<strong>解释：</strong>可拼接成的回文串为 <code>["battab","tabbat"]</code></pre>

<p><strong>示例 3：</strong></p>

<pre>
<strong>输入：</strong>words = ["a",""]
<strong>输出：</strong>[[0,1],[1,0]]
</pre>
 

<p><strong>提示：</strong></p>

<ul>
	<li><code>1 <= words.length <= 5000</code></li>
	<li><code>0 <= words[i].length <= 300</code></li>
	<li><code>words[i]</code> 由小写英文字母组成</li>
</ul>


## template

```java
class Solution {
	private static List<List<Integer>> ans = new ArrayList<>();

	public List<List<Integer>> palindromePairs(String[] words) {
		if (words == null || words.length == 0) {
			return null;
		}

		ans = new ArrayList<>();
		TrieNode root = new TrieNode();

		for (int i = 0; i < words.length; i++) {
			addWord(root, words[i], i);
		}

		for (int i = 0; i < words.length; i++) {
			find(root, words[i], i);
		}
		return ans;
	}

	private static class TrieNode {

		int index;
		TrieNode[] next;
		List<Integer> palindIndex;

		public TrieNode() {
			index = -1;
			next = new TrieNode[26];
			palindIndex = new ArrayList<>();
		}
	}

	private static void addWord(TrieNode root, String word, int index) {
		for (int i = word.length() - 1; i >= 0; i--) {
			int ch = word.charAt(i) - 'a';
			if (root.next[ch] == null) {
				root.next[ch] = new TrieNode();
			}

			if (isPalindrome(word, 0, i)) {
				root.palindIndex.add(index);
			}
			root = root.next[ch];
		}
		root.index = index;
		root.palindIndex.add(index);
	}

	private static void find(TrieNode root, String word, int index) {
		for (int i = 0; i < word.length(); i++) {

			if (root.index != -1 && root.index != index && isPalindrome(word, i, word.length() - 1)) {
				ans.add(Arrays.asList(index, root.index));
			}

			if (root.next[word.charAt(i) - 'a'] == null) {
				return;
			}
			root = root.next[word.charAt(i) - 'a'];
		}

		for (int i : root.palindIndex) {
			if (i != index) {
				ans.add(Arrays.asList(index, i));
			}
		}
	}

	private static boolean isPalindrome(String string, int l, int r) {
		while (l < r) {
			if (string.charAt(l++) != string.charAt(r--)) {
				return false;
			}
		}
		return true;
	}
}


```

## 答案

```java

```

## 选项

### A

```java

```

### B

```java

```

### C

```java

```