Palindrome Pairs
2016-07-01 15:12
323 查看
public class Solution { public List<List<Integer>> palindromePairs(String[] words) { List<List<Integer>> ret = new ArrayList<>(); if (words == null || words.length < 2) return ret; Map<String, Integer> map = new HashMap<String, Integer>(); for (int i=0; i<words.length; i++) map.put(words[i], i); for (int i=0; i<words.length; i++) { // System.out.println(words[i]); for (int j=0; j<=words[i].length(); j++) { // notice it should be "j <= words[i].length()" String str1 = words[i].substring(0, j); String str2 = words[i].substring(j); if (isPalindrome(str1)) { String str2rvs = new StringBuilder(str2).reverse().toString(); if (map.containsKey(str2rvs) && map.get(str2rvs) != i) { List<Integer> list = new ArrayList<Integer>(); list.add(map.get(str2rvs)); list.add(i); ret.add(list); // System.out.printf("isPal(str1): %s\n", list.toString()); } } if (isPalindrome(str2)) { String str1rvs = new StringBuilder(str1).reverse().toString(); // check "str.length() != 0" to avoid duplicates if (map.containsKey(str1rvs) && map.get(str1rvs) != i && str2.length()!=0) { List<Integer> list = new ArrayList<Integer>(); list.add(i); list.add(map.get(str1rvs)); ret.add(list); // System.out.printf("isPal(str2): %s\n", list.toString()); } } } } return ret; } private boolean isPalindrome(String str) { int left = 0; int right = str.length() - 1; while (left <= right) { if (str.charAt(left++) != str.charAt(right--)) return false; } return true; } }
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])
相关文章推荐
- offsetof ,container_of ,typeof 用法
- 获取类的路径
- http://m.blog.csdn.net/article/details?id=49132747
- __name__ == '__main__'
- 史上最强大的Saiku开发资源总结
- leetcode 172. Factorial Trailing Zeroes
- 217. Contains Duplicate && 219. Contains Duplicate II && 220. Contains Duplicate III
- Paint House II
- nextResponder与Responder Chain
- alter table <表名 > add constraint <主键名>用法
- 服务器TIME_WAIT和CLOSE_WAIT详解和解决办法
- Codeforces-687B Remainders Game
- Facebook 开源 AI 所使用的硬件平台 'Big Sur'
- Facebook 开源 AI 所使用的硬件平台 'Big Sur'
- mybatis报错 Parameter 'list' not found. Available parameters are [1, 0, param1, param2]
- pyinstaller打出的EXE包执行时报错“failed to excute ”信息
- bzoj 3540: [Usaco2014 Open]Fair Photography
- http://blog.csdn.net/lmj623565791/article/details/51635533
- Gradle project sync failed. Please fix your project and try again解决办法
- Print Article[HDU 3507,2010 ACM-ICPC Multi-University Training Contest]