[LeetCode] Shifting Letters II

2381. Shifting Letters II

You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.

Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that ‘z’ becomes ‘a’). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that ‘a’ becomes ‘z’).

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
14
15
16
17
18
19
20
21
22
class Solution {
public:
string shiftingLetters(string s, vector<vector<int>>& shifts) {
vector<int> change(s.length() + 1);
for(auto& sh : shifts) {
int s = sh[0], e = sh[1], dir = sh[2];
if(dir == 1) {
change[s] += 1;
change[e + 1] -= 1;
} else {
change[s] -= 1;
change[e + 1] += 1;
}
}
for(int i = 0; i < s.length(); i++) {
if(i) change[i] += change[i - 1];
change[i] %= 26;
s[i] = ((s[i] - 'a' + change[i] + 26) % 26) + 'a';
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/20/PS/LeetCode/shifting-letters-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.