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.
解法:
对于每一个word, 拆分成前后两部分, 如果其中任意一部分本身是palindrome, 查看另一部分的reverse是否存在。 存在即可连接成为palindrome。
需要注意的是如果有word为空,因为会跳过最内层for循环,因此要单独处理。
public class Solution { public List<List<Integer>> palindromePairs(String[] words) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Map<String, Integer> wordToIndex = new HashMap<String, Integer>();; for (int i = 0; i < words.length; i++) { wordToIndex.put(words[i], i); } for (int i = 0; i < words.length; i++) { String word = words[i]; if (word.length() == 0) { for (int j = 0; j < words.length; j++) { if (isPalindrome(words[j]) && j != i) { List<Integer> pair = new ArrayList<Integer>(); pair.add(i); pair.add(j); result.add(pair); } } } for (int index = 0; index < word.length(); index++) { String firstHalf = word.substring(0, index); String secondHalf = word.substring(index, word.length()); String reversedSecond = new StringBuilder(secondHalf).reverse().toString(); String reversedFirst = new StringBuilder(firstHalf).reverse().toString(); if (isPalindrome(firstHalf) && wordToIndex.containsKey(reversedSecond) && wordToIndex.get(reversedSecond) != i) { List<Integer> pair = new ArrayList<Integer>(); pair.add(wordToIndex.get(reversedSecond)); pair.add(i); result.add(pair); } if (isPalindrome(secondHalf) && wordToIndex.containsKey(reversedFirst) && wordToIndex.get(reversedFirst) != i) { List<Integer> pair = new ArrayList<Integer>(); pair.add(i); pair.add(wordToIndex.get(reversedFirst)); result.add(pair); } } } return result; } private boolean isPalindrome(String a) { for (int i = 0, j = a.length() - 1; i <= j; i++, j--) { if (a.charAt(i) != a.charAt(j)) { return false; } } return true; } }