-
Notifications
You must be signed in to change notification settings - Fork 1
/
PalindromePairs.java
68 lines (61 loc) · 2.05 KB
/
PalindromePairs.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.smlnskgmail.jaman.leetcodejava.hard;
import java.util.*;
// https://leetcode.com/problems/palindrome-pairs/
public class PalindromePairs {
private final String[] input;
public PalindromePairs(String[] input) {
this.input = input;
}
public List<List<Integer>> solution() {
Map<String, Integer> map = new HashMap<>();
Set<Integer> set = new TreeSet<>();
int n = input.length;
for (int i = 0; i < n; i++) {
String curr = input[i];
map.put(curr, i);
set.add(curr.length());
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
String curr = input[i];
int l = curr.length();
if (l == 1) {
if (map.containsKey("")) {
result.add(Arrays.asList(i, map.get("")));
result.add(Arrays.asList(map.get(""), i));
continue;
}
}
String rev = new StringBuilder(curr).reverse().toString();
if (map.getOrDefault(rev, i) != i) {
result.add(Arrays.asList(i, map.get(rev)));
}
for (int j : set) {
if (j == l) {
break;
}
if (isPalindrome(rev, 0, l - 1 - j)) {
String s = rev.substring(l - j);
if (map.containsKey(s)) {
result.add(Arrays.asList(i, map.get(s)));
}
}
if (isPalindrome(rev, j, l - 1)) {
String s = rev.substring(0, j);
if (map.containsKey(s)) {
result.add(Arrays.asList(map.get(s), i));
}
}
}
}
return result;
}
private boolean isPalindrome(String s, int l, int r) {
while (l < r) {
if (s.charAt(l++) != s.charAt(r--)) {
return false;
}
}
return true;
}
}