-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
70 lines (51 loc) · 2.08 KB
/
Copy pathsolution.java
File metadata and controls
70 lines (51 loc) · 2.08 KB
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
69
70
class Solution {
// Function to check palindrome
private boolean isPalindrome(String s, int left, int right) {
// Compare both ends
while(left < right) {
// Mismatch means not palindrome
if(s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public boolean palindromePair(String[] arr) {
// Store strings with index
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < arr.length; i++) {
map.put(arr[i], i);
}
// Traverse all words
for(int i = 0; i < arr.length; i++) {
String word = arr[i];
int n = word.length();
// Try every split position
for(int j = 0; j <= n; j++) {
String left = word.substring(0, j);
String right = word.substring(j);
// CASE 1
if(isPalindrome(word, 0, j - 1)) {
// Reverse right part
String revRight = new StringBuilder(right).reverse().toString();
// Check existence
if(map.containsKey(revRight) && map.get(revRight) != i) {
return true;
}
}
// CASE 2
if(j != n && isPalindrome(word, j, n - 1)) {
// Reverse left part
String revLeft = new StringBuilder(left).reverse().toString();
// Check existence
if(map.containsKey(revLeft) && map.get(revLeft) != i) {
return true;
}
}
}
}
return false;
}
}