래원

[LeetCode] 2381. Shifting Letters II (Python) 본문

알고리즘/LeetCode

[LeetCode] 2381. Shifting Letters II (Python)

Laewon Jeong 2025. 1. 5. 21:42

 

난이도: Medium

 

문제 설명


 

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.

 

문제 예제


Example 1:

Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
Output: "ace"
Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".
Finally, shift the characters from index 0 to index 2 forward. Now s = "ace".

Example 2:

Input: s = "dztz", shifts = [[0,0,0],[1,1,1]]
Output: "catz"
Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".
Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".

 

제한 사항


  • 1 <= s.length, shifts.length <= 5 * 10^4
  • shifts[i].length == 3
  • 0 <= starti <= endi < s.length
  • 0 <= directioni <= 1
  • s consists of lowercase English letters.

 

✏️Solution(솔루션)


class Solution:
    def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
        s = list(s)
        total_shift = [0 for _ in range(len(s)+1)]
        
        for start, end, d in shifts:
            if d == 1:
                total_shift[start] += 1
                total_shift[end+1] -= 1
            else:
                total_shift[start] -= 1
                total_shift[end+1] += 1
        
        for i in range(len(s)):
            if i > 0:
                total_shift[i] += total_shift[i-1]

            shift_alpha = ord(s[i]) + (total_shift[i] % 26)

            if shift_alpha > ord('z'):
                shift_alpha -= 26
            elif shift_alpha < ord('a'):
                shift_alpha += 26

            s[i] = chr(shift_alpha)

        return ''.join(s)

 

먼저 문자열 s의 요소를 바꾸기 쉽게 하기 위해 리스트로 변환해주었다.

 

그리고 각 문자 위치의 이동량을 저장하기 위해 total_shift라는 리스트를 만들었다.

 

이제 shifts에 주어진 각 범위를 가지고 total_shift를 업데이트 해주었다. 

 

direction_i가 1이면 total_shift[start]에 +1을 해주고 total_shift[end+1]에는 -1을 해주었다.

direction_i가 0이면 total_shift[start]에 -1을 해주고 total_shift[end+1]에는 +1을 해주었다.

 

다음으로, total_shift에 누적합을 계산하여 각 문자에 적용할 총 이동량을 구했다.

ex)

- shifts[i] = [1, 4, 1]

- total_shift = [0, 1, 0, 0, 0, -1, ...]

- 누적합 적용 => total_shift = [0, 1, 1, 1, 1, 0, ...]

 

이제 각 s[i] 마다 total_shift[i]를 더해 shift 시켜주면 된다.

 


문제: 2381. Shifting Letters II

 

깃허브: github

 

algorithm_practice/LeetCode/2465-shifting-letters-ii at main · laewonJeong/algorithm_practice

하루 한 문제 챌린지. Contribute to laewonJeong/algorithm_practice development by creating an account on GitHub.

github.com