LeetCode-in-Java

2514. Count Anagrams

Hard

You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '.

A string t is an anagram of string s if the ith word of t is a permutation of the ith word of s.

Return the number of distinct anagrams of s. Since the answer may be very large, return it modulo 109 + 7.

Example 1:

Input: s = “too hot”

Output: 18

Explanation: Some of the anagrams of the given string are “too hot”, “oot hot”, “oto toh”, “too toh”, and “too oht”.

Example 2:

Input: s = “aa”

Output: 1

Explanation: There is only one anagram possible for the given string.

Constraints:

Solution

import java.util.Arrays;

public class Solution {
    private static final int MOD = (int) 1e9 + 7;

    public int countAnagrams(String s) {
        var charArray = s.toCharArray();
        long ans = 1L;
        long mul = 1L;
        var cnt = new int[26];
        int j = 0;
        for (char c : charArray) {
            if (c == ' ') {
                Arrays.fill(cnt, 0);
                j = 0;
            } else {
                mul = mul * ++cnt[c - 'a'] % MOD;
                ans = ans * ++j % MOD;
            }
        }
        return (int) (ans * pow(mul, MOD - 2) % MOD);
    }

    private long pow(long x, int n) {
        var res = 1L;
        for (; n > 0; n /= 2) {
            if (n % 2 > 0) {
                res = res * x % MOD;
            }
            x = x * x % MOD;
        }
        return res;
    }
}