We have a string
Call the shift of a letter, the next letter in the alphabet, (wrapping around so that
For example,
Now for each
Return the final string after all such shifts to
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"
Approach
Java
public class ShiftingLetters {public static void main(String[] args) {String S = "abc";int[] shifts = { 3, 5, 9 };System.out.println(shiftingLetters(S, shifts));}static String shiftingLetters(String S, int[] shifts) {StringBuffer sb = new StringBuffer();int n = S.length();long sum = 0;for (int i = n - 1; i >= 0; i--) {sum += shifts[i];long x = (sum + S.charAt(i) - 'a');x = x % 26;sum = sum % 26;sb.append((char)('a' + x));}sb.reverse();return sb.toString();}}
C++
#include <bits/stdc++.h>using namespace std;string shiftingLetters(string S, vector<int> &shifts){string str = "";int n = S.size();long long sum = 0;for (int i = n - 1; i >= 0; i--){sum += shifts[i];long long x = (sum + S[i] - 'a');x = x % 26;sum = sum % 26;str += 'a' + x;}reverse(str.begin(), str.end());return str;}int main(){string S = "abc";vector<int> shifts = {3, 5, 9};cout << shiftingLetters(S, shifts);return 0;}
No comments:
Post a Comment