[Oracle] LeetCode 848. Shifting Letters
You are given a string s of lowercase English letters and an integer array shifts of the same length.
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.
Solution
使用后缀数组即可。对于第 \(i\) 个位置的字符,偏移之后则为:
\[a+(s[i]-a+pref[i])\%26
\]
点击查看代码
class Solution {
private:
string ans="";
long long pref[100002];
public:
string shiftingLetters(string s, vector<int>& shifts) {
int n = shifts.size();
for(int i=n-1;i>=0;i--){
pref[i] = shifts[i]+pref[i+1];
}
for(int i=0;i<n;i++){
ans+= (char)('a'+ (s[i]-'a'+pref[i])%26);
}
return ans;
}
};
浙公网安备 33010602011771号