LeetCode 267. Palindrome Permutation II

Code is not that clean....

First find out how many odd number of characters.... if there are more than one, it can't form palindrome.

If there is only one odd number character, if the odd number is one, we only need to permute the even/2 number characters.

                                                                   if the odd number is more than one, we need to permute (odd + 1) / 2 characters + the even/2 number characters.

Suppose we have  "aabb"---> it can form permutation for sure, we only need to permute ab, and then append the reverse of them to form the permutation.

Suppose we have "aabbc" --> we do the same as above, but append c in the middle.

Suppose we have "aabbccc" --> we need to perform permutation for abcc  --> append the other c in the middle.

#include 
#include 
#include 
#include 
using namespace std;
/*
  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 [];
*/
void permuteString(string tmp, string path, vector& res) {
  if(tmp == "") {res.push_back(path); return;}
  for(int i = 0; i < tmp.size(); ++i) {
    if(i > 0 && (tmp[i] == tmp[i-1])) continue;
    string remaining = tmp.substr(0, i) + tmp.substr(i + 1);
    permuteString(remaining, path + tmp[i], res);
  }
}

vector palindromePermutation(string s) {
  vector res;
  string path = "";
  vector charMap(26, 0);
  for(int i = 0; i < s.size(); ++i) {
    charMap[s[i] - 'a']++;
  }
  int oddCount = 0;
  for(int i = 0; i < 26; ++i) {
    if(charMap[i] % 2) {
      oddCount++;
      if(oddCount > 1) return {};
    }
  }
  string tmp = "";
  for(int i = 0; i < 26; ++i) {
      if((charMap[i] % 2 != 0) && (charMap[i] > 1)) {
        for(int j = 0; j < (charMap[i] + 1) / 2; ++j) tmp += (i + 'a');
      } else if(charMap[i] > 0){
        for(int j = 0; j < charMap[i] / 2; ++j) tmp += (i + 'a');
      }
  }
  permuteString(tmp, path, res);
  string oddChar = "";
  for(int i = 0; i < 26; ++i) {
    if(charMap[i] % 2 != 0) oddChar += (i + 'a');
  }
  vector result;
  for(int i = 0; i < res.size(); ++i) {
    string a = res[i];
    reverse(a.begin(), a.end());
    string tmp = res[i] + oddChar + a;
    result.push_back(tmp);
  }
  return result;
}
int main(void) {
  vector res = palindromePermutation("aabbccc");
  for(int i = 0;  i< res.size(); ++i) cout << res[i] << endl;
}


你可能感兴趣的:(LeetCode,题解)