336. Palindrome Pairs
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:
Input: [“abcd”,“dcba”,“lls”,“s”,“sssll”]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are [“dcbaabcd”,“abcddcba”,“slls”,“llssssll”]
Example 2:
Input: [“bat”,“tab”,“cat”]
Output: [[0,1],[1,0]]
Explanation: The palindromes are [“battab”,“tabbat”]
solution 1 Brute Force
尝试每种combination得到最终结果,但是会提醒time limit exceeded
public class PalindromePairs {
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<>();
int len = words.length;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
if (i == j) continue;
StringBuffer str = new StringBuffer();
str.append(words[i]);
str.append(words[j]);
if (isPalindrome(str.toString())) {
List<Integer> tmp = new ArrayList<>();
tmp.add(i);
tmp.add(j);
res.add(tmp);
}
}
}
return res;
}
public boolean isPalindrome(String s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}
}
solution 2: HashMap
使用HashMap可以查询某个字符串是否存在。
遍历n个字符串,每个字符串拆成两部分,
S
t
r
i
n
g
s
t
r
1
=
w
o
r
d
s
[
i
]
.
s
u
b
s
t
r
i
n
g
(
0
,
j
)
String str1 = words[i].substring(0,j)
Stringstr1=words[i].substring(0,j)和
S
t
r
i
n
g
s
t
r
2
=
w
o
r
d
s
[
i
]
.
s
u
b
s
t
r
i
n
g
(
j
)
String str2 = words[i].substring(j)
Stringstr2=words[i].substring(j)。
如果str1是回文,同时map中存在str2的reverse,words[k],说明words[k]和owrds[i]会组成一个回文;
对于str2同理,区别是concatenation的顺序不太一样,words[i]和words[k]会组成回文;
举例:
words = {“sssll”,“s”,“lls”};
假设遍历的字符串是"sssll" (index = 0),当 j = 2时,str1 = “ss”, str2 = “sll”,str1是回文,同时str2的reverse是"lls",map中存在"lls" (index = 2),所以[2,0]组成一个回文。
class Solution {
public boolean isPalindrome(String s) {
int l = 0;
int r = s.length() - 1;
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) return false;
}
return true;
}
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
int len = words.length;
for (int i = 0; i < len; i++)
map.put(words[i],i);
for (int i = 0; i < len; i++) {
for (int j = 0; j <= words[i].length();j++) {
String str1 = words[i].substring(0,j);
String str2 = words[i].substring(j);
if (isPalindrome(str1)) {
String tmp = new StringBuffer(str2).reverse().toString();
if (map.containsKey(tmp) && map.get(tmp) != i) {
List<Integer> tmpList = new ArrayList<>();
tmpList.add(map.get(tmp));
tmpList.add(i);
res.add(tmpList);
}
}
if (isPalindrome(str2)) {
String tmp = new StringBuffer(str1).reverse().toString();
// check str2.length()!=0 to avoid duplicates
if (map.containsKey(tmp) && map.get(tmp) != i && str2.length()!=0) {
List<Integer> tmpList = new ArrayList<>();
tmpList.add(i);
tmpList.add(map.get(tmp));
res.add(tmpList);
}
}
}
}
return res;
}
}
Trie Node
参考Trie