[LeetCode] Number of Strings Which Can Be Rearranged to Contain Substring

2931. Maximum Spending After Buying Items

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:

  • The string "lteer" is good because we can rearrange it to form "leetr" .
  • "letl" is not good because we cannot rearrange it to contain "leet" as a substring.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
long long dp[101010][3][2][2];
class Solution {
long long mod = 1e9 + 7;
long long helper(int n, int e, int l, int t) {
if(n == 0) return e == 0 and l == 0 and t == 0;
long long& res = dp[n][e][l][t];
if(res != -1) return res;
res = helper(n-1,e,l,t) * (26 - (e > 0) - (l > 0) - (t > 0)) % mod;
if(e) {
res = (res + helper(n-1,e-1,l,t)) % mod;
}
if(l) {
res = (res + helper(n - 1, e,l-1,t)) % mod;
}
if(t) {
res = (res + helper(n-1, e, l, t-1)) % mod;
}
return res;
}
public:
int stringCount(int n) {
memset(dp,-1,sizeof dp);
return helper(n,2,1,1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/12/PS/LeetCode/number-of-strings-which-can-be-rearranged-to-contain-substring/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.