2025-05-13 Daily Challenge
Today I have done leetcode's May LeetCoding Challenge with cpp
.
May LeetCoding Challenge 13
Description
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
.
Example 1:
Input: s = "abcyy", t = 2
Output: 7
Explanation:
- First Transformation (t = 1):
<ul> <li><code>'a'</code> becomes <code>'b'</code></li> <li><code>'b'</code> becomes <code>'c'</code></li> <li><code>'c'</code> becomes <code>'d'</code></li> <li><code>'y'</code> becomes <code>'z'</code></li> <li><code>'y'</code> becomes <code>'z'</code></li> <li>String after the first transformation: <code>"bcdzz"</code></li> </ul> </li> <li><strong>Second Transformation (t = 2)</strong>: <ul> <li><code>'b'</code> becomes <code>'c'</code></li> <li><code>'c'</code> becomes <code>'d'</code></li> <li><code>'d'</code> becomes <code>'e'</code></li> <li><code>'z'</code> becomes <code>"ab"</code></li> <li><code>'z'</code> becomes <code>"ab"</code></li> <li>String after the second transformation: <code>"cdeabab"</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>"cdeabab"</code>, which has 7 characters.</li>
Example 2:
Input: s = "azbk", t = 1
Output: 5
Explanation:
- First Transformation (t = 1):
<ul> <li><code>'a'</code> becomes <code>'b'</code></li> <li><code>'z'</code> becomes <code>"ab"</code></li> <li><code>'b'</code> becomes <code>'c'</code></li> <li><code>'k'</code> becomes <code>'l'</code></li> <li>String after the first transformation: <code>"babcl"</code></li> </ul> </li> <li><strong>Final Length of the string</strong>: The string is <code>"babcl"</code>, which has 5 characters.</li>
Constraints:
1 <= s.length <= 105
s
consists only of lowercase English letters.1 <= t <= 105
Solution
class Solution {
const int MOD = 1e9 + 7;
public:
int lengthAfterTransformations(string s, int t) {
vector<int> dp(26);
for(auto c : s) {
dp[c - 'a'] += 1;
}
for(int i = 0; i < t; ++i) {
rotate(dp.rbegin(), dp.rbegin() + 1, dp.rend());
dp[1] += dp[0];
dp[1] %= MOD;
}
int answer = 0;
for(int i = 0; i < 26; ++i) {
answer += dp[i];
answer %= MOD;
}
return answer;
}
};
// Accepted
// 824/824 cases passed (261 ms)
// Your runtime beats 59.11 % of cpp submissions
// Your memory usage beats 65.52 % of cpp submissions (20.4 MB)