Skip to content

Commit fd42b5c

Browse files
committed
Add solution #848
1 parent 603e24c commit fd42b5c

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -655,6 +655,7 @@
655655
845|[Longest Mountain in Array](./0845-longest-mountain-in-array.js)|Medium|
656656
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
657657
847|[Shortest Path Visiting All Nodes](./0847-shortest-path-visiting-all-nodes.js)|Hard|
658+
848|[Shifting Letters](./0848-shifting-letters.js)|Medium|
658659
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
659660
868|[Binary Gap](./0868-binary-gap.js)|Easy|
660661
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|

solutions/0848-shifting-letters.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 848. Shifting Letters
3+
* https://leetcode.com/problems/shifting-letters/
4+
* Difficulty: Medium
5+
*
6+
* You are given a string s of lowercase English letters and an integer array shifts of the
7+
* same length.
8+
*
9+
* Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that
10+
* 'z' becomes 'a').
11+
*
12+
* For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
13+
*
14+
* Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.
15+
*
16+
* Return the final string after all such shifts to s are applied.
17+
*/
18+
19+
/**
20+
* @param {string} s
21+
* @param {number[]} shifts
22+
* @return {string}
23+
*/
24+
var shiftingLetters = function(s, shifts) {
25+
const cumulativeShifts = new Array(s.length).fill(0);
26+
27+
cumulativeShifts[s.length - 1] = shifts[s.length - 1] % 26;
28+
for (let i = s.length - 2; i >= 0; i--) {
29+
cumulativeShifts[i] = (cumulativeShifts[i + 1] + shifts[i]) % 26;
30+
}
31+
32+
let result = '';
33+
for (let i = 0; i < s.length; i++) {
34+
const charCode = s.charCodeAt(i);
35+
const shiftedCode = ((charCode - 97 + cumulativeShifts[i]) % 26) + 97;
36+
result += String.fromCharCode(shiftedCode);
37+
}
38+
39+
return result;
40+
};

0 commit comments

Comments
 (0)