Leetcode Palindrome Permutation I & II

本文介绍了一种算法,用于给定字符串的所有可能回文子串划分及生成所有不重复的回文排列。通过递归回溯实现字符串的有效划分,并采用位运算检查字符频率来生成回文排列。

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

[
  ["aa","b"],
  ["a","a","b"]
]
给一个string, 返回所有的回文。


    public List<List<String>> partition(String s) {
        List<List<String>> list = new ArrayList<>();
        backtrack(list, new ArrayList<String>(), s, 0);
        return list;
    }
    
    private void backtrack(List<List<String>> list, List<String> temp, String s, int start) {
        if (start == s.length()) list.add(new ArrayList<String>(temp));
        else {
            for (int i = start; i < s.length(); i++) {
                if (isPalindrome(s, start, i)) {
                    temp.add(s.substring(start, i + 1));
                    backtrack(list, temp, s, i + 1); i+1 避免重复
                    temp.remove(temp.size() - 1);
                }
            }
        }
    }
    
    private boolean isPalindrome(String s, int low, int high) {
        while (low < high) {
            if (s.charAt(low++) != s.charAt(high--)) return false;
        }
        return true;
    }

Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.

For example:

Given s = "aabb", return ["abba", "baab"].

Given s = "abc", return [].

思路是:找单个出现的字母,如果多余两个则返回[]


    public List<String> generatePalindromes(String s) {
        int[] map = new int[256];
        for (char c : s.toCharArray()) map[c]++;
        List<String> res = new ArrayList<>();
        String mid = null;
        for (int i = 0; i < map.length; i++) {
            if (map[i] % 2 == 1) {
                if (mid == null) mid = String.valueOf((char) i);
                else return res;
            }
        }
        helper(res, (mid == null) ? "" : mid, map, s.length());
        return res;
    }
    
    private void helper(List<String> res, String tmp, int[] map, int len) {
        if (tmp.length() == len) {
            res.add(tmp);
            return;
        }
        for (int i = 0; i < map.length; i++) {
            if (map[i] >= 2) {
                map[i] -= 2;
                helper(res, (char) i + tmp + (char) i, map, len);
                map[i] += 2;
            }
        }
    }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值