Shifting Letters LeetCode Solution - The Coding Shala
Home >> LeetCode >> Shifting Letters
Other Posts You May Like
In this post, we will learn how to solve LeetCode's Shifting Letters Problem and will implement its solution in Java.
Shifting Letters Problem
We have a string S of lowercase letters, and an integer array shifts. Call the shift of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a'). For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'. Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times. Return the final string after all such shifts to S are applied.
Example 1:
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.
Practice this problem on LeetCode(Click Here).
Shifting Letters Java Solution
Approach 1
The last character of the string only shifts number shifts[length-1] times. The second last character of string shifts number shifts[length-1] + shifts[length-2] times, and like this first character shifts the sum of all the numbers in shifts array times.
Java Program:
class Solution { public String shiftingLetters(String S, int[] shifts) { long currShift = 0; for(int i=0; i<shifts.length; i++) { currShift += shifts[i]; } StringBuilder sb = new StringBuilder(); long ch = S.charAt(0) - 97; if(currShift%26 != 0) ch = (ch + currShift) % 26; sb.append((char)( ch+97)); for(int i=1; i<shifts.length; i++){ currShift -= shifts[i-1]; ch = S.charAt(i) - 97; if(currShift%26 != 0) ch = (ch + currShift)%26; sb.append((char) (ch+97)); } return sb.toString(); } }
- LeetCode - Valid Boomerang
- LeetCode - Split a String in Balanced Strings
- LeetCode - Consecutive Characters
- LeetCode - Range Sum Query Immutable
- LeetCode - Crawler Log Folder
Comments
Post a Comment