|
6 | 6 | import java.util.List;
|
7 | 7 | import java.util.Map;
|
8 | 8 |
|
9 |
| -/** |
| 9 | +/**336. Palindrome Pairs |
| 10 | + * |
10 | 11 | * 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.
|
11 | 12 |
|
12 | 13 | Example 1:
|
|
20 | 21 | */
|
21 | 22 | public class _336 {
|
22 | 23 |
|
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 | + } |
29 | 31 |
|
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 | + } |
43 | 48 | }
|
44 | 49 | }
|
| 50 | + return pairs; |
45 | 51 | }
|
46 |
| - return pairs; |
47 |
| - } |
48 | 52 |
|
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 | + } |
53 | 58 | }
|
| 59 | + return true; |
54 | 60 | }
|
55 |
| - return true; |
56 | 61 | }
|
57 |
| - |
58 | 62 | }
|
0 commit comments