Shifting Letters LeetCode Solution - The Coding Shala

Home >> LeetCode >> Shifting Letters

 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();
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala