Leetcode 336. Palindrome Pairs- FB tag

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"]
 思路:

两个for循环,外层循环数组,内层循环单词的character,然后取character的0,j个,然后检查palindrome, 来个str2的reverse, 然后去map里面检查有没有这个str2rev,有的话就可以写到list里了,不过0是map.get(str2rvs),  1 是 i。因为是str1的回文,2的时候是调转的并且要检查str2是否是空字符。

class Solution {

public List> palindromePairs(String[] words) {
    List> ret = new ArrayList<>(); 
    if (words == null || words.length < 2) return ret;
    Map map = new HashMap();
    for (int i=0; i list = new ArrayList();
                    list.add(map.get(str2rvs));
                    list.add(i);
                    ret.add(list);    // System.out.printf("isPal(str1): %s\n", list.toString());
                }
            }
            if (isPalindrome(str2)) { 
                String str1rvs = new StringBuilder(str1).reverse().toString();
                // check "str.length() != 0" to avoid duplicates
                if (map.containsKey(str1rvs) && map.get(str1rvs) != i && str2.length()!=0) { 
                    List list = new ArrayList();
                    list.add(i);
                    list.add(map.get(str1rvs));
                    ret.add(list);
                    // System.out.printf("isPal(str2): %s\n", list.toString());
                }
            }
        }
    }
    return ret;
}

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

你可能感兴趣的:(leetcode)