LeetCode 풀기 - 2381. Shifting Letters II

백지우·2026년 9월 28일

LeetCode

목록 보기
74/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

2381. Shifting Letters II

풀이

  • 방법: shift 하나마다 글자 하나씩 바꾸니 시간초과 -> 움직여야 하는 만큼 미리 저장해둔 뒤 한번에 글자 위치 이동
class Solution {
    public String shiftingLetters(String s, int[][] shifts) {
        StringBuilder res = new StringBuilder(s);
        int[] move = new int[s.length() + 1];

        for (int[] shift : shifts) {
            int start = shift[0];
            int end = shift[1];

            if (shift[2] == 1) {
                move[start]++;
                move[end + 1]--;
            } else {
                move[start]--;
                move[end + 1]++;
            }
        }

        int curMove = 0;

        for (int i = 0; i < s.length(); i++) {
            curMove += move[i];

            int shift = ((curMove % 26) + 26) % 26;

            char c = (char) ('a' + (res.charAt(i) - 'a' + shift) % 26);
            res.setCharAt(i, c);
        }

        return res.toString();
    }
}

0개의 댓글