LeetCode 2381: Shifting Letters II

ArrayStringPrefix Sum

Problem Description

Explanation

To solve this problem, we can iterate through the shifts array in reverse order and keep track of the cumulative shifts for each character. We can then apply the final shift to each character in the string to get the result.

  1. Initialize a variable shiftCount to store the cumulative shift count.
  2. Iterate through the shifts array in reverse order.
  3. For each shift, update the shiftCount by adding the difference between endi and starti multiplied by directioni.
  4. Iterate through the string s in reverse order.
  5. For each character, calculate the new character after applying the cumulative shift.
  6. Update the character in the string s.
  7. Return the final string s.

Solutions

class Solution {
    public String shiftingLetters(String s, int[][] shifts) {
        int n = s.length();
        long shiftCount = 0;
        
        for (int i = shifts.length - 1; i >= 0; i--) {
            int start = shifts[i][0];
            int end = shifts[i][1];
            int direction = shifts[i][2];
            shiftCount += (end - start + 1) * (long) direction;
        }
        
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            int shift = (int) (shiftCount % 26);
            char newChar = (char) ('a' + (c - 'a' + shift) % 26);
            sb.append(newChar);
            shiftCount -= shift;
        }
        
        return sb.toString();
    }
}

Loading editor...