|
| 1 | +const mod = 1e9 + 7 |
| 2 | +const fact = Array(1e5 + 2) |
| 3 | +getfact() |
| 4 | +// console.log(fact) |
| 5 | +/** |
| 6 | + * @param {string} s |
| 7 | + * @return {number} |
| 8 | + */ |
| 9 | +const countAnagrams = function (s) { |
| 10 | + let ans = 1 |
| 11 | + const arr = s.trim().split(' ') |
| 12 | + for (const word of arr) { |
| 13 | + ans = modmul(ans, ways(word)) |
| 14 | + } |
| 15 | + |
| 16 | + return ans |
| 17 | +} |
| 18 | + |
| 19 | +function modmul(a, b) { |
| 20 | + const big = BigInt |
| 21 | + return Number(((big(a) % big(mod)) * (big(b) % big(mod))) % big(mod)) |
| 22 | +} |
| 23 | + |
| 24 | +function binExpo(a, b) { |
| 25 | + if (b === 0) return 1 |
| 26 | + let res = binExpo(a, Math.floor(b / 2)) |
| 27 | + if (b & 1) { |
| 28 | + return modmul(a, modmul(res, res)) |
| 29 | + } else { |
| 30 | + return modmul(res, res) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +function modmulinv(a) { |
| 35 | + return binExpo(a, mod - 2) |
| 36 | +} |
| 37 | + |
| 38 | +function getfact() { |
| 39 | + fact[0] = 1 |
| 40 | + for (let i = 1; i <= 100001; i++) { |
| 41 | + fact[i] = modmul(fact[i - 1], i) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +function ways(str) { |
| 46 | + const freq = Array(26).fill(0) |
| 47 | + const a = 'a'.charCodeAt(0) |
| 48 | + for (let i = 0; i < str.length; i++) { |
| 49 | + freq[str.charCodeAt(i) - a]++ |
| 50 | + } |
| 51 | + |
| 52 | + let totalWays = fact[str.length] |
| 53 | + |
| 54 | + let factR = 1 |
| 55 | + for (let i = 0; i < 26; i++) { |
| 56 | + factR = modmul(factR, fact[freq[i]]) |
| 57 | + } |
| 58 | + // console.log(freq, totalWays, factR) |
| 59 | + return modmul(totalWays, modmulinv(factR)) |
| 60 | +} |
0 commit comments