Leetcode 848. Shifting Letters
You have 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’).
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.
Input: s = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation: We start with “abc”.
Arriving at “rpl” by shifting:
s
always non-empty?s
and shifts
?shifts
non-negative?shifts
array from end to start, accumulating the effect of shifts.s
by shifting the characters according to the values in the modified shifts
array.For shifts = [3, 5, 9]
:
shifts[2] = 9
(no change)shifts[1] = 5 + shifts[2] = 5 + 9 = 14
shifts[0] = 3 + shifts[1] = 3 + 14 = 17
Updated shifts
array would be [17, 14, 9]
.
#include <vector>
#include <string>
std::string shiftingLetters(std::string s, std::vector<int>& shifts) {
int n = shifts.size();
// Accumulate shifts from the end to start
for (int i = n - 2; i >= 0; --i) {
shifts[i] += shifts[i + 1];
shifts[i] %= 26; // Reduce to keep within bounds (a-z)
}
shifts[n - 1] %= 26; // also handle the last element
// Apply shifts to string s
for (int i = 0; i < n; ++i) {
s[i] = (s[i] - 'a' + shifts[i]) % 26 + 'a';
}
return s;
}
n
is the length of shifts
.Thus, the overall time complexity is O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?