Input: s ="abc", shifts =[3,5,9]Output: "rpl"Explanation: We start with"abc".After shifting the first 1 letters of s by 3, we have "dbc".After shifting the first 2 letters of s by 5, we have "igc".After shifting the first 3 letters of s by 9, we have "rpl", the answer.
To efficiently apply multiple overlapping shifts, we can process the shifts array from right to left, accumulating the total shifts needed for each character. This way, each character is shifted by the sum of all relevant shifts, avoiding repeated work.
classSolution {
public String shiftingLetters(String s, int[] shifts) {
int n = s.length();
char[] ans =newchar[n];
long total = 0;
for (int i = n - 1; i >= 0; --i) {
total = (total + shifts[i]) % 26;
ans[i]= (char)('a'+ (s.charAt(i) -'a'+ (int)total) % 26);
}
returnnew String(ans);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funshiftingLetters(s: String, shifts: IntArray): String {
val n = s.length
val ans = CharArray(n)
var total = 0Lfor (i in n - 1 downTo 0) {
total = (total + shifts[i]) % 26 ans[i] = 'a' + ((s[i] - 'a' + total.toInt()) % 26)
}
return String(ans)
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defshiftingLetters(self, s: str, shifts: list[int]) -> str:
n = len(s)
ans: list[str] = [''] * n
total: int =0for i in range(n -1, -1, -1):
total = (total + shifts[i]) %26 ans[i] = chr((ord(s[i]) - ord('a') + total) %26+ ord('a'))
return''.join(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnshifting_letters(s: String, shifts: Vec<i32>) -> String {
let n = s.len();
letmut ans =vec!['a'; n];
letmut total =0i64;
let s_bytes = s.as_bytes();
for i in (0..n).rev() {
total = (total + shifts[i] asi64) %26;
ans[i] = ((s_bytes[i] -b'a'+ total asu8) %26+b'a') aschar;
}
ans.into_iter().collect()
}
}