[LeetCode] Shifting Letters

848. Shifting Letters

You are given a string s of lowercase English letters and an integer array shifts of the same length.

Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that ‘z’ becomes ‘a’).

  • For example, shift(‘a’) = ‘b’, shift(‘t’) = ‘u’, and shift(‘z’) = ‘a’.

Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.

Return the final string after all such shifts to s are applied.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string shiftingLetters(string s, vector<int>& shifts) {
int sum = 0, mod = 26, n = s.length();
for(int i = n - 1; i >= 0; i--) {
sum = (sum + shifts[i]) % mod;
int offset = s[i] - 'a';
offset = (offset + sum) % mod;
s[i] = offset + 'a';
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/09/PS/LeetCode/shifting-letters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.