例题
分析:
不难看出答案等于每个word的异构字符串个数的乘积,问题变成了如何求word的异构字符串个数
令word的长度为n,10^9 + 7为p
那么
乘法取模都会,但是如何对除法取模?这里需要用到 乘法逆元 的知识
乘法逆元
定义:如果一个线性同余方程,则 为 的逆元
快速幂解法:
因为
由费马小定理:
所以:
所以:
费马小定理
定义:若p为素数,,则
另一种形式
证明:
数学归纳法
显然 ,假设 成立,那么通过二项式定理有
因为 成立
在模 意义下
那么
将 带入得 得证
代码
class Solution {
int mod = (int) 1e9 + 7;
public int countAnagrams(String s) {
String[] arr = s.split(" ");
int n = arr.length;
long res = 1;
for (int i = 0; i < n; i++) {
res = res * func(arr[i]) % mod;
}
return (int) res;
}
public long func(String s) {
int n = s.length();
long mul = 1;
long a = 1;
int[] cnt = new int[26];
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int j = c - 'a';
cnt[j]++;
mul = mul * (i + 1) % mod;
a = a * cnt[j] % mod;
}
return mul * quickPow(a, mod - 2) % mod;
}
public long quickPow(long x, long y) {
if (y == 0) return 1;
long res = 1;
if (y % 2 == 0) {
res = quickPow(x * x % mod, y / 2);
} else {
res = res * x % mod;
res = res * quickPow(x, y - 1) % mod;
}
return res;
}
}