Given a string s and array shifts, return a final string with letters shifted such that shifts[i] decides the number of letters to be shifted in the string s
Constraints: 1 < shifts[i] < s.length()
Ex1:
s = "abcd" shifts = [1,2,3,4]
Step1: one character is shifted by 1: "bbcd"
Step2: two characters are shifted by 1: "cccd"
Step3: three characters are shifted by 1: "dddd"
Step4: four characters are shifted by 1: "eeee"
Ex2:
s = "aez", shifts = [1,1,3]
Step1: one character is shifted by 1: "bez"
Step2: one character is shifted by 1: "cez"
Step3: three characters are shifted by 1: "dfa"
Ex2:
s = "abc", shifts = [2,2,2]
Step1: two character are shifted by 1: "bcc"
Step2: two characters are shifted by 1: "cdc"
Step3: two characters are shifted by 1: "dec"
I could only come up with naive brute force solution which ran into Timed out exception
Can someone help with a better version?
public String shiftingLetters(String s, int[] shifts) {
char[] chArray = new char[s.length()];
chArray = s.toCharArray();
for(int i= 0; i<shifts.length; i++) {
int iter = shifts[i];
while(iter > 0) {
chArray[iter-1]++;
if (chArray[iter-1] > 'z') {
chArray[iter-1] -= 26;
}
iter--;
}
}
return String.valueOf(chArray);
}This question is slightly different from Shift letters
This is my first post. correct me if there are any mistakes