回文字符串是指从左到右和从右到左相同的字符串,现给定一个仅由小写字母组成的字符串,你可以把它的字母重新排列,以形成不同的回文字符串。 输入:非空仅由小写字母组成的字符串,长度不超过100; 输出:能组成的所有回文串的个数(因为结果可能非常大,输出对1000000007取余数的结果)。 例如:输入"aabb" 输出为2(因为“aabb”对应的所有回文字符串有2个:abba和baab)
#include <iostream> #include <string> using namespace std; int palindrome(const string &s) { int count[26]; for (int i = 0; i < 26; i++) { count[i] = 0; } int len = s.size(); for (int i = 0; i < len; i++) { count[s[i]-'a']++; } int countOfOdd = 0; for (int i = 0; i < 26; i++) { if (count[i] & 1) { countOfOdd++; } count[i] >>= 1; } if (countOfOdd > 1) { return 0; } long long int result = 1; int totalLen = 0; for (int i = 0; i < 26; i++) { if (count[i] > 1) { bool first = true; int factor = 1; while (count[i]) { result = result*(totalLen+1); if (!first) { result /= factor; } totalLen++; count[i]--; result %= 1000000007; if (first) { first = false; } factor++; } } else if (count[i]) { result = result*(totalLen+1); totalLen++; result %= 1000000007; } } return result; }