[LeetCode]336. Palindrome Pairs

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

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


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

public class Solution {
    public List<List<Integer>> palindromePairs(String[] words) {
        List<List<Integer>> res = new LinkedList();
        HashMap<String, Integer> 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<Integer> 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<Integer> 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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值