热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PalindromePairs解答

Question

Question



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.

Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]



Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]

Answer

Brute-force的做法是两层for循环,遍历每个string,看有无string可以与之匹配为palindrome。

较好的做法是利用HashMap。

对于String a来说,考虑两种情况:

1. a为空,则a与集合中任意已经对称的string可以组成结果

2. a不为空。

则有三种情况:

a. reverse(a)在集合中

b. a[0..i]对称,且reverse(a[i + 1,...,n])在集合中。如"#bc", "cba"

c. a[i,..,n]对称,且reverse(a[0,...,i])在集合中。如"abcc", "ba"

public class Solution {
public List List Integer palindromePairs(String[] words) {
List List Integer result = new ArrayList ();
if (words == null || words.length == 0) {
return result;
}
// Record each string position
Map String, Integer map = new HashMap ();
Set Integer palindromeSet = new HashSet ();
int len = words.length;
for (int i = 0; i len; i++) {
map.put(words[i], i);
if (isPalindrome(words[i])) {
palindromeSet.add(i);
}
}
// Traverse
for (int i = 0; i len; i++) {
String word = words[i];
if (word.length() == 0) {
for (int index : palindromeSet) {
addResult(result, i, index);
}
}
int l = word.length();
for (int j = 0; j j++) {
String frOnt= word.substring(0, j);
String back = word.substring(j, l);
String rFrOnt= reverse(front);
String rBack = reverse(back);
if (isPalindrome(front) map.containsKey(rBack)) {
addResult(result, map.get(rBack), i);
}
if (isPalindrome(back) map.containsKey(rFront)) {
addResult(result, i, map.get(rFront));
}
}
}
return result;
private String reverse(String s) {
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
private void addResult(List List Integer result, int start, int end) {
if (start == end) {
return;
}
List Integer indexes = new ArrayList ();
indexes.add(start);
indexes.add(end);
result.add(indexes);
private boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i j) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
}


   



推荐阅读
author-avatar
kk1049057
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有