[LeetCode] 336. Palindrome Pairs

linspiration發表於2019-01-19

Problem

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.

Example 1:

Input: [“abcd”,”dcba”,”lls”,”s”,”sssll”]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are [“dcbaabcd”,”abcddcba”,”slls”,”llssssll”]
Example 2:

Input: [“bat”,”tab”,”cat”]
Output: [[0,1],[1,0]]
Explanation: The palindromes are [“battab”,”tabbat”]

Solution

class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> res = new ArrayList<>();
        if (words == null || words.length == 0) return res;
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            map.put(words[i], i);
        }
        
        if (map.containsKey("")) {
            int blankIndex = map.get("");
            for (int i = 0; i < words.length; i++) {
                if (isPalindrome(words[i]) && i != blankIndex) {
                    res.add(Arrays.asList(blankIndex, i));
                    res.add(Arrays.asList(i, blankIndex));
                }
            }
        }
        
        for (int i = 0; i < words.length; i++) {
            String reversed = new StringBuilder(words[i]).reverse().toString();
            if (map.containsKey(reversed)) {
                int index = map.get(reversed);
                if (index != i) {
                    res.add(Arrays.asList(i, index));
                }
            }
        }
        
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            for (int j = 1; j < word.length(); j++) {
                if (isPalindrome(word.substring(0, j))) {
                    String reversed = new StringBuilder(word.substring(j)).reverse().toString();
                    if (map.containsKey(reversed)) {
                        int index = map.get(reversed);
                        if (index != i) {
                            res.add(Arrays.asList(index, i));
                        }
                    }
                }
                if (isPalindrome(word.substring(j))) {
                    String reversed = new StringBuilder(word.substring(0, j)).reverse().toString();
                    if (map.containsKey(reversed)) {
                        int index = map.get(reversed);
                        if (index != i) {
                            res.add(Arrays.asList(i, index));
                        }
                    }
                }
            }
        }
        
        return res;
    }
    
    private boolean isPalindrome(String word) {
        if (word == null || word.length() <= 1) return true;
        int i = 0, j = word.length()-1;
        while (i < j) {
            if (word.charAt(i) != word.charAt(j)) return false;
            i++;
            j--;
        }
        return true;
    }
}

相關文章