【快速幂+逆元】先以空格将字符串分割,对于每一部分求排列的个数,公式为n! / (a1! * a2! * ... ak!) ai为字符串中重复元素的个数,由于需要对相除后的结果取模,但是很明显在乘的时候就要取模,所以要分开取模。但是对除法的取模很麻烦,于是就要用到逆元求a1!...ak!的逆元,求出逆元后就可以把除法变为乘法了。
逆元公式:c逆 = c ^ (mod - 2) % mod
阶乘逆元打表公式:infact[i] = infact[i - 1] * qmi(i, mod - 2, mod) % mod
class Solution {
// 48:10
public long qmi(long a, long b, long p) {
long res = 1;
while (b != 0) {
if (1 == (b & 1)) res = res * a % p;
b >>= 1;
a = a * a % p;
}
return res;
}
public int countAnagrams(String s) {
int n = s.length();
long mod = (long)1e9 + 7;
long[] fact = new long[n + 1], infact = new long[n + 1];
fact[0] = infact[0] = 1;
for (int i = 1; i <= n; i++) {
fact[i] = fact[i - 1] * i % mod;
infact[i] = infact[i - 1] * qmi(i, mod - 2, mod) % mod;
}
String[] strs = s.split(" ");
long ans = 1;
for (String str: strs) {
int m = str.length();
int[] cnt = new int[26];
for (int i = 0; i < m; i++) {
char c = str.charAt(i);
cnt[c - 'a']++;
}
long tmp = fact[m];
for (int i = 0; i < 26; i++) {
tmp = tmp * infact[cnt[i]] % mod;
}
ans = ans * tmp % mod;
}
return (int)ans;
}
}
class Solution {
public:
// 24:17
const int mod = 1e9 + 7;
long long qmi(long long a, long long b) {
long long res = 1;
while (b) {
if (b & 1) res = res * a % mod;
b >>= 1;
a = a * a % mod;
}
return res;
}
int countAnagrams(string s) {
int m = s.length();
long long fact[m + 1], infact[m + 1];
fact[0] = infact[0] = 1;
for (int i = 1; i <= m; i++) {
fact[i] = fact[i - 1] * i % mod;
infact[i] = infact[i - 1] * qmi(i, mod - 2) % mod;
}
stringstream ssin(s);
vector<string> strs;
string str;
while (ssin >> str) strs.push_back(str);
long long ans = 1;
for (string str: strs) {
int n = str.length();
int cnt[26] = {0};
for (int i = 0; i < n; i++) cnt[str[i] - 'a']++;
ans = ans * fact[n] % mod;
for (int i = 0; i < 26; i++) {
if (cnt[i] > 1) ans = ans * infact[cnt[i]] % mod;
}
}
return (int)ans;
}
};
【优化】下面除数的逆元我们是分开算的,其实可以把除数都乘起来再求逆元
class Solution {
public:
const int mod = 1e9 + 7;
long long qmi(long long a, long long b) {
long long res = 1;
while (b) {
if (b & 1) res = res * a % mod;
b >>= 1;
a = a * a % mod;
}
return res;
}
int countAnagrams(string s) {
int m = s.length();
long long fact[m + 1];
fact[0] = 1;
for (int i = 1; i <= m; i++) fact[i] = fact[i - 1] * i % mod;
stringstream ssin(s);
vector<string> strs;
string str;
while (ssin >> str) strs.push_back(str);
long long ans = 1, mul = 1;
for (string str: strs) {
int n = str.length();
int cnt[26] = {0};
for (int i = 0; i < n; i++) cnt[str[i] - 'a']++;
ans = ans * fact[n] % mod;
for (int i = 0; i < 26; i++) {
if (cnt[i] > 1) mul = mul * fact[cnt[i]] % mod;
}
}
ans = ans * qmi(mul, mod - 2) % mod;
return ans;
}
};