3335. Total Characters in String After Transformations I
Description
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.
Example 1:
Input: s = "abcyy", t = 2
Output: 7
Explanation:
- First Transformation (t = 1):
'a'becomes'b''b'becomes'c''c'becomes'd''y'becomes'z''y'becomes'z'- String after the first transformation:
"bcdzz"
- Second Transformation (t = 2):
'b'becomes'c''c'becomes'd''d'becomes'e''z'becomes"ab"'z'becomes"ab"- String after the second transformation:
"cdeabab"
- Final Length of the string: The string is
"cdeabab", which has 7 characters.
Example 2:
Input: s = "azbk", t = 1
Output: 5
Explanation:
- First Transformation (t = 1):
'a'becomes'b''z'becomes"ab"'b'becomes'c''k'becomes'l'- String after the first transformation:
"babcl"
- Final Length of the string: The string is
"babcl", which has 5 characters.
Constraints:
1 <= s.length <= 105sconsists only of lowercase English letters.1 <= t <= 105
Solutions
Solution 1: Recurrence
Thinking
Each step shifts a letter forward, and \(\texttt{z}\) becomes \(\texttt{ab}\). With \(t \le 10^5\) we cannot rewrite the string.
Only the \(26\) letter counts matter. \(f[i][j]\) is the count of letter \(j\) after \(i\) steps: \(\texttt{z}\) feeds \(\texttt{a}\) and \(\texttt{b}\), and every other letter comes from the previous one.
The answer is the sum of \(f[t]\), taken modulo \(10^9+7\).
We define \(f[i][j]\) to represent the count of the \(j\)-th letter in the alphabet after \(i\) transformations. Initially, \(f[0][j]\) is the count of the \(j\)-th letter in the string \(s\).
After each transformation, the count of the \(j\)-th letter in the alphabet can be calculated as follows:
The answer is \(f[t][0] + f[t][1] + \ldots + f[t][25]\).
Since the answer can be very large, we take the result modulo \(10^9 + 7\).
The time complexity is \(O(t \times |\Sigma|)\), and the space complexity is \(O(t \times |\Sigma|)\), where \(|\Sigma|\) is the size of the alphabet.
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
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 | |
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |