leetcode 266.Palindrome Permutation 、267.Palindrome Permutation II

266.Palindrome Permutation

https://www.cnblogs.com/grandyang/p/5223238.html

判断一个字符串的全排列能否形成一个回文串。

能组成回文串,在字符串长度为偶数的情况下,每个字符必须成对出现;奇数的情况下允许一个字符单独出现,其他字符都必须成对出现。用一个set对相同字符进行加减即可。

class Solution {
public:
    /**
     * @param s: the given string
     * @return: if a permutation of the string could form a palindrome
     */
    bool canPermutePalindrome(string &s) {
        // write your code here
        unordered_set<char> container;
        for(auto c : s){
            if(container.find(c) != container.end())
                container.erase(c);
            else
                container.insert(c);
        }
        return container.empty() || container.size() == 1;
    }
};

 

267.Palindrome Permutation II

https://www.cnblogs.com/grandyang/p/5315227.html 

class Solution {
public:
    /**
     * @param s: the given string
     * @return: all the palindromic permutations (without duplicates) of it
     */
    vector<string> generatePalindromes(string &s) {
        // write your code here
        vector<string> res;
        string mid = "";
        int number = 0;
        unordered_map<char,int> m;
        for(auto c : s)
            m[c]++;
        for(auto& it : m){
            if(it.second % 2 == 1)
                mid += it.first;
            it.second /= 2;
            number += it.second;
            if(mid.size() > 1)
                return res;
        }
        generatePalindromes(m,number,res,mid,"");
        return res;
    }
    void generatePalindromes(unordered_map<char,int> m,int number,vector<string>& res,string mid,string out){
        if(out.size() == number){
            res.push_back(out + mid + string(out.rbegin(),out.rend()));
            return;
        }
        for(auto& it : m){
            if(it.second > 0){
                it.second--;
                generatePalindromes(m,number,res,mid,out + it.first);
                it.second++;
            }
        }
    }
};

 

转载于:https://www.cnblogs.com/ymjyqsx/p/10969920.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值