-
Notifications
You must be signed in to change notification settings - Fork 37
/
336 Palindrome Pairs
38 lines (29 loc) · 1.13 KB
/
336 Palindrome Pairs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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"]
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> result = new ArrayList();
int n = words.length;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(isPalindrome(words[i]+words[j])){
result.add(Arrays.asList(i,j));
}
if(isPalindrome(words[j]+words[i])){
result.add(Arrays.asList(j,i));
}
}
}
return result;
}
static boolean isPalindrome(String temp){
int i = 0;
int j = temp.length()-1;
while(i<j){
if(temp.charAt(i)!=temp.charAt(j)) return false;
i++;j--;
}
return true;
}