xinyu04

导航

[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

维护一个后缀数组 \(suf\),那么更新则为

\[(s[i]-a+suf[i])\%26+a \]

点击查看代码
class Solution {
private:
    long suf[100003];
    string ans = "";
public:
    string shiftingLetters(string s, vector<int>& shifts) {
        int n = s.size();
        suf[n-1] = shifts[n-1];
        for(int i=n-2;i>=0;i--){
            suf[i] = suf[i+1]+(long)shifts[i];
        }
        for(int i=0;i<n;i++){
            ans += (s[i]-'a'+suf[i])%26+'a';
        }
        return ans;
    }
};

posted on 2022-10-26 05:33  Blackzxy  阅读(9)  评论(0编辑  收藏  举报