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: Dynamic Programming
- Time complexity: O(n+t)
- Space complexity: O(t)
JavaScript
js
/**
* @param {string} s
* @param {number} t
* @return {number}
*/
const lengthAfterTransformations = function (s, t) {
const MODULO = BigInt(10 ** 9 + 7);
const BASE_CODE = 'a'.charCodeAt(0);
const memo = new Map();
let result = 0n;
const getTransformCharSize = code => {
if (code < 26) return 1n;
if (memo.has(code)) return memo.get(code);
const nextT = code - 26;
const a = getTransformCharSize(0 + nextT);
const b = getTransformCharSize(1 + nextT);
const total = (a + b) % MODULO;
memo.set(code, total);
return total;
};
for (const char of s) {
const code = char.charCodeAt(0) - BASE_CODE;
const length = getTransformCharSize(code + t);
result = (result + length) % MODULO;
}
return Number(result);
};