Skip to content

Commit f647ed0

Browse files
refactor 336
1 parent 404aae7 commit f647ed0

File tree

1 file changed

+32
-28
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+32
-28
lines changed

src/main/java/com/fishercoder/solutions/_336.java

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
import java.util.List;
77
import java.util.Map;
88

9-
/**
9+
/**336. Palindrome Pairs
10+
*
1011
* 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.
1112
1213
Example 1:
@@ -20,39 +21,42 @@
2021
*/
2122
public class _336 {
2223

23-
public List<List<Integer>> palindromePairs(String[] words) {
24-
List<List<Integer>> pairs = new ArrayList();
25-
Map<String, Integer> map = new HashMap();
26-
for (int i = 0; i < words.length; i++) {
27-
map.put(words[i], i);
28-
}
24+
public static class Solution1 {
25+
public List<List<Integer>> palindromePairs(String[] words) {
26+
List<List<Integer>> pairs = new ArrayList();
27+
Map<String, Integer> map = new HashMap();
28+
for (int i = 0; i < words.length; i++) {
29+
map.put(words[i], i);
30+
}
2931

30-
for (int i = 0; i < words.length; i++) {
31-
int l = 0;
32-
int r = 0;
33-
while (l <= r) {
34-
String s = words[i].substring(l, r);
35-
Integer j = map.get(new StringBuilder(s).reverse().toString());
36-
if (j != null && j != i && isPalindrome(words[i].substring(l == 0 ? r : 0, l == 0 ? words[i].length() : l))) {
37-
pairs.add(Arrays.asList(l == 0 ? new Integer[]{i, j} : new Integer[]{j, i}));
38-
}
39-
if (r < words[i].length()) {
40-
r++;
41-
} else {
42-
l++;
32+
for (int i = 0; i < words.length; i++) {
33+
int l = 0;
34+
int r = 0;
35+
while (l <= r) {
36+
String s = words[i].substring(l, r);
37+
Integer j = map.get(new StringBuilder(s).reverse().toString());
38+
if (j != null && j != i && isPalindrome(
39+
words[i].substring(l == 0 ? r : 0, l == 0 ? words[i].length() : l))) {
40+
pairs.add(
41+
Arrays.asList(l == 0 ? new Integer[] {i, j} : new Integer[] {j, i}));
42+
}
43+
if (r < words[i].length()) {
44+
r++;
45+
} else {
46+
l++;
47+
}
4348
}
4449
}
50+
return pairs;
4551
}
46-
return pairs;
47-
}
4852

49-
private boolean isPalindrome(String s) {
50-
for (int i = 0; i < s.length() / 2; i++) {
51-
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
52-
return false;
53+
private boolean isPalindrome(String s) {
54+
for (int i = 0; i < s.length() / 2; i++) {
55+
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
56+
return false;
57+
}
5358
}
59+
return true;
5460
}
55-
return true;
5661
}
57-
5862
}

0 commit comments

Comments
 (0)