zoukankan      html  css  js  c++  java
  • 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++;
                }
            }
        }
    };
  • 相关阅读:
    每周学算法/读英文/知识点心得分享 1.28
    ARTS 1.21
    ARTS 1.14
    ARTS 1.7
    ARTS 12.31
    ARTS 12.24
    Leetcode : Median of Two Sorted Arrays
    我是怎样改善遗留系统的
    《大话重构》免费送书活动开始啦
    我的新书终于要出来啦
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10969920.html
Copyright © 2011-2022 走看看