LeetCode-in-Java

2930. Number of Strings Which Can Be Rearranged to Contain Substring

Medium

You are given an integer n.

A string s is called good if it contains only lowercase English characters and it is possible to rearrange the characters of s such that the new string contains "leet" as a substring.

For example:

Return the total number of good strings of length n.

Since the answer may be large, return it modulo 109 + 7.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: n = 4

Output: 12

Explanation: The 12 strings which can be rearranged to have “leet” as a substring are: “eelt”, “eetl”, “elet”, “elte”, “etel”, “etle”, “leet”, “lete”, “ltee”, “teel”, “tele”, and “tlee”.

Example 2:

Input: n = 10

Output: 83943898

Explanation: The number of strings with length 10 which can be rearranged to have “leet” as a substring is 526083947580. Hence the answer is 526083947580 % (109 + 7) = 83943898.

Constraints:

Solution

public class Solution {
    private long pow(long x, long n, long mod) {
        long result = 1;
        long p = x % mod;
        while (n != 0) {
            if ((n & 1) != 0) {
                result = (result * p) % mod;
            }
            p = (p * p) % mod;
            n >>= 1;
        }
        return result;
    }

    public int stringCount(int n) {
        long mod = (int) 1e9 + 7L;
        return (int)
                (((+pow(26, n, mod)
                                                - (n + 75) * pow(25, n - 1L, mod)
                                                + (2 * n + 72) * pow(24, n - 1L, mod)
                                                - (n + 23) * pow(23, n - 1L, mod))
                                        % mod
                                + mod)
                        % mod);
    }
}