336. Palindrome Pairs
Hard
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:
Input: [“abcd”,“dcba”,“lls”,“s”,“sssll”]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are [“dcbaabcd”,“abcddcba”,“slls”,“llssssll”]
Example 2:
Input: [“bat”,“tab”,“cat”]
Output: [[0,1],[1,0]]
Explanation: The palindromes are [“battab”,“tabbat”]
题意
给定一个字符串数组,找到数组中的两个不同的字符串,拼接之后可以成为回文字符串
思路
字符串s和字符串t拼接成回文字符串的4种情况:
- s是回文字符串 && t是空串 || t是回文字符串 && s是空串 => s + t, t + s都是回文字符串
- t是s的逆序 => s + t, t + s都是回文字符串
- s可以分为s1, s2 st. s1 + s2 == s && s1是回文字符串 && s2是t的逆序 => t + s是回文字符串
- s可以分为s1, s2 st. s1 + s2 == s && s1是t的逆序 && s2是回文字符串 => s + t是回文字符串
用字典树存储字符串数组,可以实现O(w)的字符串查找效率。算法总的时间复杂度为O(nw),其中n是字符串数组的长度,w是最长的字符串的长度。
代码
class Solution {
class TrieNode {
public int index = -1;
public TrieNode[] next = new TrieNode[26];
public TrieNode(int _index) {
index = _index;
}
}
private void addPair(List<List<Integer>> ans, int n1, int n2) {
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(n1);
tmp.add(n2);
ans.add(tmp);
}
private boolean checkPalindrome(String s) {
int i = 0