Shifting Letters in C++

C++Server Side ProgrammingProgramming

Suppose we have a string S of lowercase letters, and an integer array shifts. The shift of a letter means the next letter in the alphabet, for z, it will be a. Now for each shifts[i] = x, we want to shift the first i+1 letters of S, x times. We have to find the final string after all such shifts to S are applied. So if the string is “abc” and shifts = [3,5,9], then after shifting the first 1 letter of S by 3, will have “dbc”, shifting first two letters of S by 5, we have “igc”, and shifting first 3 letters of S by 9, we have “rpl”, and this is the answer.

To solve this, we will follow these steps −

  • for i in range size of shift array – 2 down to 0
    • shift[i] := shift[i] + shift[i + 1]
    • shift[i] := shift[i] mod 26
  • for i in range 0 to size of S – 1
    • S[i] := ((S[i] – ASCII of a) + shifts[i] mod 26) + ASCII of a
  • return S

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string shiftingLetters(string S, vector<int>& shifts) {
      for(int i = shifts.size() - 2 ;i >=0; i--){
         shifts[i] += shifts[i + 1];
         shifts[i] %= 26;
      }
      for(int i = 0; i < S.size(); i++) {
         S[i] = ( ((S[i] - 'a') + shifts[i]) % 26 + 'a');
      }
      return S;
   }
};
main(){
   vector<int> v = {3,5,9};
   Solution ob;
   cout << (ob.shiftingLetters("abc", v));
}

Input

"abc"
[3,5,9]

Output

rpl
raja
Updated on 05-May-2020 10:27:18

Advertisements