848. Shifting Letters ¶ Time: $O(n)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: string shiftingLetters(string s, vector<int>& shifts) { string ans; for (int i = shifts.size() - 2; i >= 0; --i) shifts[i] = (shifts[i] + shifts[i + 1]) % 26; for (int i = 0; i < s.length(); ++i) ans += (s[i] - 'a' + shifts[i]) % 26 + 'a'; return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public String shiftingLetters(String s, int[] shifts) { StringBuilder sb = new StringBuilder(); for (int i = shifts.length - 2; i >= 0; --i) shifts[i] = (shifts[i] + shifts[i + 1]) % 26; for (int i = 0; i < s.length(); ++i) sb.append((char) ((s.charAt(i) - 'a' + shifts[i]) % 26 + 'a')); return sb.toString(); } } 1 2 3 4 5 6 7 8 9 10 11class Solution: def shiftingLetters(self, s: str, shifts: list[int]) -> str: ans = [] for i in reversed(range(len(shifts) - 1)): shifts[i] += shifts[i + 1] for c, shift in zip(s, shifts): ans.append(chr((string.ascii_lowercase.index(c) + shift) % 26 + ord('a'))) return ''.join(ans)