Palindrome permutation
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code", False, "aab" True, "carerac" .
Hint:
- Consider the palindromes of odd vs even length. What difference does you notice?
- Count the frequency of each character.
- If Each character occurs even number of times, then it must is a palindrome. How about character which occurs odd number of times
1 classSolution {2 Public:3 BOOLCanpermutepalindrome (strings) {4vector<int> cnt ( the,0);5 for(auto a:s) + +Cnt[a];6 BOOLFlag =false;7 for(Auto n:cnt)if(N &1) {8 if(!flag) flag =true;9 Else return false;Ten } One return true; A } -};
Palindrome permutation II
Given A string s , return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could is form.
For example:
Given s = "aabb" , return ["abba", "baab"] .
Given s = "abc" , return [] .
Hint:
- If a palindromic permutation exists, we just need to generate the first half of the string.
- To generate all distinct permutations of a (half of) strings, use a similar approach from:permutations II or Next permutat Ion.
Do not follow the prompts, direct use of DFS, do not know the character does not meet the requirements.
1 classSolution {2 Public:3 voidDFS (vector<string> &res, vector<int> &cnt,string&s,intLintr) {4 if(L >=r) {5 Res.push_back (s);6 return;7 }8 for(inti =0; I < cnt.size (); ++i)if(Cnt[i] >=2) {9Cnt[i]-=2;TenS[L] = S[r] =i; OneDFS (RES, CNT, S, L +1+ U-1); ACnt[i] + =2; - } - } thevector<string> Generatepalindromes (strings) { -vector<int> cnt ( the,0); - for(auto a:s) + +Cnt[a]; - BOOLFlag =false; + for(inti =0; I < cnt.size (); ++i)if(Cnt[i] &1) { - if(!flag) { +Flag =true; AS[s.length ()/2] =i; at}Else { - return {}; - } - } -vector<string>Res; -DFS (RES, CNT, S,0, S.length ()-1); in returnRes; - } to};
[Leetcode] Palindrome permutation I & II