[LeetCode] 267. Palindrome Permutation II 回文全排列 II

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 [].

Hint:

  1. If a palindromic permutation exists, we just need to generate the first half of the string.
  2. To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation.

266. Palindrome Permutation 的拓展,266只是判断全排列是否存在回文的,此题要返回所有的回文全排列。提示:如果回文全排列存在,只需要生成前半段字符串,后面的直接根据前半段得到。用Permutations II or Next Permutation的方法去生成不同的全排列。

Python:

class Solution(object):
    def generatePalindromes(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        cnt = collections.Counter(s)
        mid = ‘‘.join(k for k, v in cnt.iteritems() if v % 2)
        chars = ‘‘.join(k * (v / 2) for k, v in cnt.iteritems())
        return self.permuteUnique(mid, chars) if len(mid) < 2 else []

    def permuteUnique(self, mid, nums):
        result = []
        used = [False] * len(nums)
        self.permuteUniqueRecu(mid, result, used, [], nums)
        return result

    def permuteUniqueRecu(self, mid, result, used, cur, nums):
        if len(cur) == len(nums):
            half_palindrome = ‘‘.join(cur)
            result.append(half_palindrome + mid + half_palindrome[::-1])
            return
        for i in xrange(len(nums)):
            if not used[i] and not (i > 0 and nums[i-1] == nums[i] and used[i-1]):
                used[i] = True
                cur.append(nums[i])
                self.permuteUniqueRecu(mid, result, used, cur, nums)
                cur.pop()
                used[i] = False

Python:

class Solution2(object):
    def generatePalindromes(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        cnt = collections.Counter(s)
        mid = tuple(k for k, v in cnt.iteritems() if v % 2)
        chars = ‘‘.join(k * (v / 2) for k, v in cnt.iteritems())
        return [‘‘.join(half_palindrome + mid + half_palindrome[::-1])                 for half_palindrome in set(itertools.permutations(chars))] if len(mid) < 2 else []

C++:

class Solution {
public:
    vector<string> generatePalindromes(string s) {
        vector<string> res;
        unordered_map<char, int> m;
        string t = "", mid = "";
        for (auto a : s) ++m[a];
        for (auto it : m) {
            if (it.second % 2 == 1) mid += it.first;
            t += string(it.second / 2, it.first);
            if (mid.size() > 1) return {};
        }
        permute(t, 0, mid, res);
        return res;
    }
    void permute(string &t, int start, string mid, vector<string> &res) {
        if (start >= t.size()) {
            res.push_back(t + mid + string(t.rbegin(), t.rend()));
        }
        for (int i = start; i < t.size(); ++i) {
            if (i != start && t[i] == t[start]) continue;
            swap(t[i], t[start]);
            permute(t, start + 1, mid, res);
            swap(t[i], t[start]);
        }
    }
};

C++:

class Solution {
public:
    vector<string> generatePalindromes(string s) {
        vector<string> res;
        unordered_map<char, int> m;
        string t = "", mid = "";
        for (auto a : s) ++m[a];
        for (auto &it : m) {
            if (it.second % 2 == 1) mid += it.first;
            it.second /= 2;
            t += string(it.second, it.first);
            if (mid.size() > 1) return {};
        }
        permute(t, m, mid, "", res);
        return res;
    }
    void permute(string &t, unordered_map<char, int> &m, string mid, string out, vector<string> &res) {
        if (out.size() >= t.size()) {
            res.push_back(out + mid + string(out.rbegin(), out.rend()));
            return;
        }
        for (auto &it : m) {
            if (it.second > 0) {
                --it.second;
                permute(t, m, mid, out + it.first, res);
                ++it.second;
            }
        }
    }
};

C++:

class Solution {
public:
    vector<string> generatePalindromes(string s) {
        vector<string> res;
        unordered_map<char, int> m;
        string t = "", mid = "";
        for (auto a : s) ++m[a];
        for (auto it : m) {
            if (it.second % 2 == 1) mid += it.first;
            t += string(it.second / 2, it.first);
            if (mid.size() > 1) return {};
        }
        sort(t.begin(), t.end());
        do {
            res.push_back(t + mid + string(t.rbegin(), t.rend()));
        } while (next_permutation(t.begin(), t.end()));
        return res;
    }
};

  

类似题目:

[LeetCode] 266. Palindrome Permutation 回文全排列  

[LeetCode] 46. Permutations 全排列

[LeetCode] 47. Permutations II 全排列 II

[LeetCode] 31. Next Permutation 下一个排列

  

原文地址:https://www.cnblogs.com/lightwindy/p/8629431.html

时间: 2024-10-11 16:57:12

[LeetCode] 267. Palindrome Permutation II 回文全排列 II的相关文章

[LeetCode#267] Palindrome Permutation II

Problem: 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

[LeetCode] Longest Palindrome 最长回文串

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the leng

LeetCode 9 Palindrome Number (回文数)

翻译 确定一个整数是否是回文数.不能使用额外的空间. 一些提示: 负数能不能是回文数呢?(比如,-1) 如果你想将整数转换成字符串,但要注意限制使用额外的空间. 你也可以考虑翻转一个整数. 然而,如果你已经解决了问题"翻转整数(译者注:LeetCode 第七题), 那么你应该知道翻转的整数可能会造成溢出. 你将如何处理这种情况? 这是一个解决该问题更通用的方法. 原文 Determine whether an integer is a palindrome. Do this without ex

LeetCode 9 Palindrome Number(回文数字判断)

Long Time No See ! 题目链接https://leetcode.com/problems/palindrome-number/?tab=Description 首先确定该数字的位数.按照已知数字x对10进行多次求余运算,可以得到数字位数. 具体思路: 1.每次取出该数字的最高位和最低位进行比较. 2.如果不相等则直接返回FALSE, 3.如果相等修改x的值(去掉最高位也同时去掉最低位)其中去掉最高位可以通过求模运算,去掉最低位可以采用除以10 4.进行循环直到x的值不大于0为止

Leetcode 9. Palindrome Number(判断回文数字)

Determine whether an integer is a palindrome. Do this without extra space.(不要使用额外的空间) Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You

[C++]LeetCode: 121 Palindrome Partitioning (分割回文子串 回溯法)

题目: 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",&

LeetCode OJ Palindrome Number(回文数)

1 class Solution { 2 public: 3 bool isPalindrome(int x) { 4 int r=0,init=x; 5 if(init==0) return true; 6 if(init<0) return false; 7 while(init!=0){ 8 r=r*10+init%10; 9 init=init/10; 10 } 11 if(r==x) 12 return true; 13 else 14 return false; 15 } 16 };

LeetCode 9. Palindrome Number(回文数)

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to

leetcode题解:Valid Palindrome(判断回文)

题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome. Note:Have you consider tha