给出一个字符串求是palindrome和anagram的比率是多少。
知识点:
1 DBL_MAX 64位double的最长数大概是1.7E308,很大很大,比long long大上不知多少倍,故此大概能容纳150!的数值,不能容纳200!的数值
2 偶数的时候,不能有字母重复为基数次,否则不能组成palindrome
3 基数的时候,只能有且只有有一个字母重复为基数次,用于放在中间的,否则也不能组成palindrome
4 计算带重复数的全排列公式:P(N) / P(M1)/P(M2)...P(Mk) 其中M1...Mk为数值出现的重复数
250分的题目,不过这250不容易拿呢,一点水分都没有的。2,3知识点不是那么好总结,1,4知识点缺一不可。
#include <string>
#include <malloc.h>
#include <algorithm>
using namespace std;
class PalindromePermutations
{
double *tbl;
public:
PalindromePermutations() : tbl((double*)malloc(sizeof(double)*51))
{
tbl[0] = 1.0;
for (int i = 1; i < 51; i++)
tbl[i] = i * tbl[i-1];
}
~PalindromePermutations()
{
free(tbl);
}
double palindromeProbability(string w)
{
int n = (int)w.size();
double numerator = tbl[n/2], denominator = tbl[n];
int odd = 0;
for (char ch = 'a'; ch <= 'z'; ch++)
{
int t = count(w.begin(), w.end(), ch);
if (t % 2 == 1) odd++;
numerator /= tbl[t/2];
denominator /= tbl[t];
}
//1.odd大于1对所有情况都不存在palindrome,2.n为偶数,只能不存在odd
if ((odd > 1) || (odd != n % 2))
return 0.0;
return numerator / denominator;
}
};