LeetCode 2381: Shifting Letters II
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.
- Initialize a variable
shiftCount
to store the cumulative shift count. - Iterate through the shifts array in reverse order.
- For each shift, update the
shiftCount
by adding the difference betweenendi
andstarti
multiplied bydirectioni
. - Iterate through the string
s
in reverse order. - For each character, calculate the new character after applying the cumulative shift.
- Update the character in the string
s
. - 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...