Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.3 kB
1
Indexable
Never
class Solution {
    int mod = 1000000007;
    public int countAnagrams(String s) {
        String[] strs = s.split(" ");
        int[] letter = new int[26];
        long res =1;
        for(String str:strs){
            int len  = str.length();
            for(char c:str.toCharArray()){
                letter[c-'a']++;
            }
            for(int val :letter){
                if(val!=0){
                    res=res*calculate(val,len)%mod;
                    len-=val;
                }
            }
            for(int i=0;i<26;i++){
                letter[i]=0;
            }
        }
        return (int)res;
    }
    public long calculate(int target,int total){
         if(target>(total-target)){
             target = total -target;
         }
         long res =1;
         for(long i=total;i>total-target;i--){
             res = res*i%mod;
         }     
         for(long i=target;i>1;i--){
             res=res * qmi(i, mod - 2) % mod;
         }
         return res;
    }
    public long qmi(long a, long k) {
        long res = 1;
        while (k > 0) {
            if ((k & 1) != 0)
                res = res * a % mod;
            a = a * a % mod;
            k >>= 1;
        }
        return res;
    }
}