Palindrome Pairs

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:
Given words = ["bat", "tab", "cat"]
Return [[0, 1], [1, 0]]
The palindromes are ["battab", "tabbat"]
Example 2:
Given words = ["abcd", "dcba", "lls", "s", "sssll"]
Return [[0, 1], [1, 0], [3, 2], [2, 4]]
The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]

大意就是找所有两个字符拼接可以组成回文的组合

    public List> palindromePairs(String[] words) {
        List> result = new ArrayList>();
        Map wordMap = new HashMap();
        for (int i = 0; i < words.length; i++) {
            wordMap.put(words[i], i);
        }
        /**
         * 两个字符串组合是否是回文的判断
         * 1.如果存在s1[0,i]是回文并且s1[i:].reverse() == s2,那么s2 + s1是回文
         * 2.如果存在s1[i:]是回文并且s1[0:i].reverse() == s2,那么s1 + s2是回文
         * 请这样理解,对于1来说,如果s1[0,i]是回文,我们可以把s[0,i]作为组合起来字符串的中间部分
         * 那么右边的部分是s1[i:],如果组合的字符串是回文的话,那么一定证明左边的部分==s1[i:].reverse()
         * 那么我们只需要在wordMap中找是否包含s1[i:].reverse()的字符即可
         * 对于2来说同理
         */
        for(int i = 0; i < words.length; i++){
            for(int j = 0; j <= words[i].length(); j++){
                String str1 = words[i].substring(0, j);
                String str2 = words[i].substring(j);

                if(isPalindrome(str1)){
                    String str2reserve = new StringBuilder(str2).reverse().toString();
                    /**
                     * wordMap.get(str2reserve) != i 避免自己和自己判断
                     */
                    if(wordMap.containsKey(str2reserve) && wordMap.get(str2reserve) != i){
                        List list = new ArrayList();
                        list.add(wordMap.get(str2reserve));
                        list.add(i);
                        result.add(list);
                    }
                }
                //str2.length() != 0 的判断是由于str1==""的时候和str2==""的时候结果是一样的,
                // 为了避免重复,str2==""的情况就不执行了
                if(isPalindrome(str2) && str2.length() != 0){
                    String str1reserve = new StringBuilder(str1).reverse().toString();
                    if(wordMap.containsKey(str1reserve) && wordMap.get(str1reserve) != i){
                        List list = new ArrayList();
                        list.add(i);
                        list.add(wordMap.get(str1reserve));
                        result.add(list);
                    }
                }
            }
        }
        return result;
    }

    private boolean isPalindrome(String str) {
        int left = 0;
        int right = str.length() - 1;
        while (left <= right) {
            if (str.charAt(left++) !=  str.charAt(right--)) {
                return false;
            }
        }
        return true;
    }

你可能感兴趣的:(Palindrome Pairs)