|
| 1 | +/** |
| 2 | + * 2381. Shifting Letters II |
| 3 | + * https://leetcode.com/problems/shifting-letters-ii/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a string s of lowercase English letters and a 2D integer array shifts where |
| 7 | + * shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the |
| 8 | + * index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters |
| 9 | + * backward if directioni = 0. |
| 10 | + * |
| 11 | + * Shifting a character forward means replacing it with the next letter in the alphabet (wrapping |
| 12 | + * around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it |
| 13 | + * with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z'). |
| 14 | + * |
| 15 | + * Return the final string after all such shifts to s are applied. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {string} s |
| 20 | + * @param {number[][]} shifts |
| 21 | + * @return {string} |
| 22 | + */ |
| 23 | +var shiftingLetters = function(s, shifts) { |
| 24 | + const compare = new Array(s.length).fill(0); |
| 25 | + for (const [start, end, direction] of shifts) { |
| 26 | + compare[start] += direction === 1 ? 1 : -1; |
| 27 | + if (end + 1 < s.length) { |
| 28 | + compare[end + 1] += direction === 1 ? -1 : 1; |
| 29 | + } |
| 30 | + } |
| 31 | + let result = ''; |
| 32 | + for (let i = 0, count = 0; i < s.length; i++) { |
| 33 | + count = (count + compare[i]) % 26; |
| 34 | + count = count < 0 ? count + 26 : count; |
| 35 | + result += String.fromCharCode((s.charCodeAt(i) - 97 + count) % 26 + 97); |
| 36 | + } |
| 37 | + return result; |
| 38 | +}; |
0 commit comments