266.Palindrome Permutationhtml
https://www.cnblogs.com/grandyang/p/5223238.htmlspa
判斷一個字符串的全排列可否造成一個迴文串。code
能組成迴文串,在字符串長度爲偶數的狀況下,每一個字符必須成對出現;奇數的狀況下容許一個字符單獨出現,其餘字符都必須成對出現。用一個set對相同字符進行加減便可。orm
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 IIhtm
https://www.cnblogs.com/grandyang/p/5315227.html blog
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++; } } } };