publicclassH336_palindromePairs{ //暴力(超时) public List<List<Integer>> palindromePairsForce(String[] words) { List<List<Integer>> returnList = new ArrayList<>(); for (int i = 0; i < words.length; i++) { for (int j = 0; j < words.length; j++) { List<Integer> list = new ArrayList<>(); String add = words[i] + words[j]; if (isPalindrome(add) && i != j) { list.add(i); list.add(j); returnList.add(list); } } } return returnList; }
publicbooleanisPalindrome(String s){ if (s.equals("")) returntrue; String[] ss = s.split(""); boolean judge = true;
for (int i = 0; i < (s.length() / 2); i++) { if (!ss[i].equals(ss[ss.length - i - 1])) judge = false; } return judge; }
//哈希表查找 public List<List<Integer>> palindromePairs(String[] words) { Map<String, Integer> reversemap = new HashMap<>(); // 将翻转后的字符串加入hashmap中 for (int i = 0; i < words.length; i++) { reversemap.put(new StringBuilder(words[i]).reverse().toString(), i); } //利用set防止前缀后缀空重复 Set<List<Integer>> nodelist = new HashSet<>(); for (int i = 0; i < words.length; i++) { String word = words[i]; //将字符串拆分为前缀后缀两部分 for (int j = 0; j <= word.length(); j++) { String left = word.substring(j); String right = word.substring(0, j); //后缀回文情况 if (isPalindrome(left)) { List<Integer> list = new ArrayList<>(); if (reversemap.containsKey(right) && i != reversemap.get(right)) { list.add(i); list.add(reversemap.get(right)); nodelist.add(list); } } //前缀回文情况 if (isPalindrome(right)) { if (reversemap.containsKey(left) && i != reversemap.get(left)) { List<Integer> list = new ArrayList<>(); list.add(reversemap.get(left)); list.add(i); nodelist.add(list); } }