Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- class Solution {
- private final long MOD = 1000000007;
- private final int maxn = 300 + 100;
- private long[] pow = new long[maxn];
- public List<List<Integer>> palindromePairs(String[] words) {
- pow[0] = 1;
- for (int i = 1; i < maxn; ++i) {
- pow[i] = pow[i - 1] * 26 % MOD;
- }
- List<Long> hash1 = Arrays.stream(words).map(word -> {
- long hash = 0;
- for (int i = 0; i < word.length(); ++i) {
- hash = (hash * 26 + word.charAt(i) - 'a' + 1) % MOD;
- }
- return hash;
- }).collect(Collectors.toList());
- List<Long> hash2 = Arrays.stream(words).map(word -> {
- long hash = 0;
- for (int i = word.length() - 1; i >= 0; --i) {
- hash = (hash * 26 + word.charAt(i) - 'a' + 1) % MOD;
- }
- return hash;
- }).collect(Collectors.toList());
- List<List<Integer>> ans = new ArrayList<>();
- for (int i = 0; i < words.length; ++i) {
- for (int j = 0; j < words.length; ++j) {
- if (i == j) {
- continue;
- }
- if ((hash1.get(i) * pow[words[j].length()] % MOD + hash1.get(j)) % MOD ==
- (hash2.get(j) * pow[words[i].length()] % MOD + hash2.get(i)) % MOD) {
- ans.add(Stream.of(i, j).collect(Collectors.toList()));
- }
- }
- }
- return ans;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement