1 public class Solution { 2 public List
> palindromePairs(String[] words) { 3 List
> ret = new ArrayList<>(); 4 if (words == null || words.length < 2) return ret; 5 Map map = new HashMap (); 6 for (int i=0; i list = new ArrayList ();16 list.add(map.get(str2rvs));17 list.add(i);18 ret.add(list);19 // System.out.printf("isPal(str1): %s\n", list.toString());20 }21 }22 if (isPalindrome(str2)) {23 String str1rvs = new StringBuilder(str1).reverse().toString();24 // check "str.length() != 0" to avoid duplicates25 if (map.containsKey(str1rvs) && map.get(str1rvs) != i && str2.length()!=0) { 26 List list = new ArrayList ();27 list.add(i);28 list.add(map.get(str1rvs));29 ret.add(list);30 // System.out.printf("isPal(str2): %s\n", list.toString());31 }32 }33 }34 }35 return ret;36 }37 38 private boolean isPalindrome(String str) {39 int left = 0;40 int right = str.length() - 1;41 while (left <= right) {42 if (str.charAt(left++) != str.charAt(right--)) return false;43 }44 return true;45 }46 }
1. j can reach word[i].length() since it can form an empty string;
2. to aviod duplication ( empty string can cause two found for a pair ,ex [abcd, dbca])