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"]

本题开始想用Trie tree来做,感觉太麻烦了,后来用了答案的方法来做的,本题可以使用hashmap来做,value值用来存储索引值,开始的时候考虑的情况不周,只考虑了类似“abcd”“dcba”这种情况,却没有考虑“lls”“s”这种情况。需要注意的是,两个字符串拼接以后是否为回文字符串,可以先判断一个字符串的左子字符串或者右子字符串是否是回文的,如果是的话,就把剩下的部分反转和另外的字符串进行比较,如果刚好是相同的,那么这个字符串拼接以后为回文字符串。值得注意的是,对于battab这种情况的,可能会算上两次,因此,在第二次判断的时候要排除掉这种情况,这种情况是两个字符串和在一起才是palindrome,所以只要排除掉一个回文子字符串的长度为0的情况即可,代码如下:

 1 public class Solution {
 2     public List<List<Integer>> palindromePairs(String[] words) {
 3         List<List<Integer>> res = new ArrayList<>();
 4         Map<String,Integer> map = new HashMap<String,Integer>();
 5         for(int i=0;i<words.length;i++) map.put(words[i],i);
 6         for(int i=0;i<words.length;i++){
 7             for(int j=0;j<=words[i].length();j++){
 8                 String str1 = words[i].substring(0,j);
 9                 String str2 = words[i].substring(j);
10                 if(isPalindrome(str1)){
11                     String str2rev = new StringBuilder(str2).reverse().toString();
12                     if(map.containsKey(str2rev)&&map.get(str2rev)!=i){
13                         List<Integer> list = new ArrayList<Integer>();
14                         list.add(map.get(str2rev));
15                         list.add(i);
16                         res.add(list);
17                     }
18                 }
19                 if(isPalindrome(str2)){
20                     String str1rev = new StringBuilder(str1).reverse().toString();
21                     if(map.containsKey(str1rev)&&map.get(str1rev)!=i&&str2.length()!=0){
22                         List<Integer> list = new ArrayList<Integer>();
23                         list.add(i);
24                         list.add(map.get(str1rev));
25                         res.add(list);
26                     }
27                 }
28             }
29         }
30         return res;
31     }
32     public boolean isPalindrome(String word){
33         int i = 0;
34         int j = word.length()-1;
35         while(i<j){
36             if(word.charAt(i)!=word.charAt(j)) return false;
37             i++;
38             j--;
39         }
40         return true;
41     }
42 }
原文地址:https://www.cnblogs.com/codeskiller/p/6597775.html