[LeetCode]336. Palindrome Pairs

https://leetcode.com/problems/palindrome-pairs/

找出两个字符串拼接可形成回文的所有组合


遍历数组,把word和所在位置加入map,再遍历数组,内层遍历当前字符串,将字符串分隔成前后两个部分,判断这两个部分是否为回文,如果是,则将另一部分翻转,并在map中找是否存在,如果存在则这两者可以构成回文

public class Solution {
    public List> palindromePairs(String[] words) {
        List> res = new LinkedList();
        HashMap map = new HashMap();
        for (int i = 0; i < words.length; i++) {
            map.put(words[i], i);
        }
        for (int j = 0; j < words.length; j++) {
            String word = words[j];
            for (int i = 0; i <= word.length(); i++) {
                String str1 = word.substring(0, i);
                String str2 = word.substring(i);
                if (isPalindrome(str1)) {
                    String str2rev = new StringBuilder(str2).reverse().toString();
                    if (map.containsKey(str2rev) && map.get(str2rev) != j) {
                        List list = new LinkedList();
                        list.add(map.get(str2rev));
                        list.add(j);
                        res.add(list);
                    }
                }
                if (isPalindrome(str2)) {
                    String str1rev = new StringBuilder(str1).reverse().toString();
                    // str2.length() != 0保证"abcd","dcba"组合时不会出现重复结果
                    if (map.containsKey(str1rev) && map.get(str1rev) != j && str2.length() != 0) {
                        List list = new LinkedList();
                        list.add(j);
                        list.add(map.get(str1rev));
                        res.add(list);
                    }
                }
            }
        }
        return res;
    }
    private boolean isPalindrome(String str) {
        int beg = 0;
        int end = str.length() - 1;
        while (beg <= end) {
            if (str.charAt(beg++) != str.charAt(end--)) {
                return false;
            }
        }
        return true;
    }
}


你可能感兴趣的:(LeetCode)