Shifting Letters of a String | String Problem | LeetCode 848

4 years ago Lalit Bhagtani 2

Problem Statement

You have given an input string of lowercase characters and an integer array shifts, perform the shift operation on each and every character of input string and return the modified string after all the shift operations are executed.

Shift operation of a letter, results the next letter of the alphabet ( wrapping applied in case of ‘z’ ).

Shift operation is defined as :-
shift[i] = x, shift the first i+1 letters of input string by x times.

Example 

Shifting Letters of a String

Input :- String = "abcd", Shift = [1, 3, 4, 5]
Output :- "nnli"
Input :- String = "abcd", Shift = [3, 5, 9, 1]
Output :- "sqme"

Solution

This problem can be solved in following steps :-

  1. Traverse the Shift array from the end (n-1, where n is the length of an array) to start (index 0). Add value at the previous index to the value at the current index and take modulus by 26 (Total number of characters in English). This step is executed to find out the total number of shift operations to be performed on each character of the input string.
  2. Create an array of characters from the input string.
  3. Traverse the String array from the start (index 0) to end (n-1, where n is the length of an array). Perform the shift operation on each and every character of an array.
  4. Convert modified array of characters to string and return it.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String result = main.shiftingLetters("abcd", new int[] {3, 5, 9, 1});
		System.out.print(result);
	}
	
	/* Solution */
	public String shiftingLetters(String S, int[] shifts) {
        
        int previous = 0;
        for(int i=shifts.length-1; i>=0; i--){            
            shifts[i] = (shifts[i] + previous) % 26;
            previous = shifts[i];
        }
        
        char[] chars = S.toCharArray();
        for(int i=0; i<chars.length; i++){
            chars[i] = (char)('a' + (((int)chars[i] + shifts[i]) % 'a') % 26);
        }
        return String.valueOf(chars);
    }
}

Result

sqme

Similar Post

  1. Custom Order Sorting of String
  2. Detect Capital in String
  3. Reverse a String

That’s all for Shifting Letters of a String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.