Skip to content

Commit f5c04d0

Browse files
committed
Add solution #2381
1 parent 064c7a1 commit f5c04d0

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,7 @@
559559
2352|[Equal Row and Column Pairs](./2352-equal-row-and-column-pairs.js)|Medium|
560560
2364|[Count Number of Bad Pairs](./2364-count-number-of-bad-pairs.js)|Medium|
561561
2375|[Construct Smallest Number From DI String](./2375-construct-smallest-number-from-di-string.js)|Medium|
562+
2381|[Shifting Letters II](./2381-shifting-letters-ii.js)|Medium|
562563
2390|[Removing Stars From a String](./2390-removing-stars-from-a-string.js)|Medium|
563564
2396|[Strictly Palindromic Number](./2396-strictly-palindromic-number.js)|Medium|
564565
2413|[Smallest Even Multiple](./2413-smallest-even-multiple.js)|Easy|

solutions/2381-shifting-letters-ii.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

Comments
 (0)