diff --git a/medium/shifting_letters_2.py b/medium/shifting_letters_2.py new file mode 100644 index 0000000..d20f829 --- /dev/null +++ b/medium/shifting_letters_2.py @@ -0,0 +1,29 @@ +# https://leetcode.com/problems/shifting-letters-ii + +from typing import List + +class Solution: + def convert(self, s: str, shift: int) -> str: + return chr( + ( + (ord(s) - ord('a') + shift) % 26 + ) + ord('a') + ) + + def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: + l = len(s) + shifting = [0] * (l + 1) + for [start, end, direction] in shifts: + if direction == 0: + shifting[start] -= 1 + shifting[end + 1] += 1 + else: + shifting[start] += 1 + shifting[end + 1] -= 1 + shift = 0 + result = [] + for i in range(len(s)): + shift += shifting[i] + result.append(self.convert(s[i], shift)) + return ''.join(result) +