LeetCode Solutions

848. Shifting Letters

Time: $O(n)$

Space: $O(n)$

			

class 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;
  }
};
			

class 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();
  }
}
			

class 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((ord(c) - ord('a') + shift) % 26 + ord('a')))

    return ''.join(ans)