LeetCode 267. Palindrome Permutation II

本文介绍了一种算法,用于找出所有可能的回文排列,并确保没有重复。通过统计字符出现次数来判断是否能形成回文串,并使用递归进行排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 <string>
#include <vector>
#include <algorithm>
#include <iostream>
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<string>& 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<string> palindromePermutation(string s) {
  vector<string> res;
  string path = "";
  vector<int> 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<string> 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<string> res = palindromePermutation("aabbccc");
  for(int i = 0;  i< res.size(); ++i) cout << res[i] << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值