码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Pairs

时间:2016-07-01 16:22:21      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

 1 public class Solution {
 2     public List<List<Integer>> palindromePairs(String[] words) {
 3     List<List<Integer>> ret = new ArrayList<>(); 
 4     if (words == null || words.length < 2) return ret;
 5     Map<String, Integer> map = new HashMap<String, Integer>();
 6     for (int i=0; i<words.length; i++) map.put(words[i], i);
 7     for (int i=0; i<words.length; i++) {
 8         // System.out.println(words[i]);
 9         for (int j=0; j<=words[i].length(); j++) { // notice it should be "j <= words[i].length()"
10             String str1 = words[i].substring(0, j);
11             String str2 = words[i].substring(j);
12             if (isPalindrome(str1)) {
13                 String str2rvs = new StringBuilder(str2).reverse().toString();
14                 if (map.containsKey(str2rvs) && map.get(str2rvs) != i) {
15                     List<Integer> list = new ArrayList<Integer>();
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 duplicates
25                 if (map.containsKey(str1rvs) && map.get(str1rvs) != i && str2.length()!=0) { 
26                     List<Integer> list = new ArrayList<Integer>();
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])

Palindrome Pairs

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/5633163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!