[LeetCode] Total Characters in String After Transformations I

3335. Total Characters in String After Transformations I

You are given a string s and an integer t, representing the number of transformations to perform. In one transformation, every character in s is replaced according to the following rules:

  • If the character is 'z', replace it with the string "ab".
  • Otherwise, replace it with the next character in the alphabet. For example, 'a' is replaced with 'b', 'b' is replaced with 'c', and so on.

Return the length of the resulting string after exactly t transformations.

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

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
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
long long mod = 1e9 + 7;
vector<vector<long long>> mul(vector<vector<long long>>& A, vector<vector<long long>>& B) {
vector<vector<long long>> res(A.size(), vector<long long>(B[0].size()));
for(int i = 0; i < res.size(); i++) {
for(int j = 0; j < res[0].size(); j++) {
for(int k = 0; k < B[0].size(); k++) {
res[i][j] = (res[i][j] + A[i][k] * B[k][j] % mod) % mod;
}
}
}
return res;
}
vector<vector<long long>> pow(vector<vector<long long>>& A, long long k) {
vector<vector<long long>> res(A.size(), vector<long long>(A.size()));
for(int i = 0; i < res.size(); i++) res[i][i] = 1;
while(k) {
if(k & 1) res = mul(res, A);
A = mul(A,A);
k>>=1;
}
return res;
}

public:
int lengthAfterTransformations(string s, int t) {
vector<vector<long long>> mat(26,vector<long long>(26)), cnt(1, vector<long long>(26));
for(int i = 0; i < 26; i++) mat[i][(i+1)%26] = 1;
mat[25][1] = 1;
for(auto& ch : s) cnt[0][ch-'a']++;
vector<vector<long long>> po = pow(mat, t);
vector<vector<long long>> mat2 = mul(cnt, po);
long long res = 0;
for(int i = 0; i < 26; i++) res = (res + mat2[0][i]) % mod;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/10/27/PS/LeetCode/total-characters-in-string-after-transformations-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.