[LeetCode] 848. Shifting Letters 漂移字母


 

We have a string 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 Sx times.

Return the final string after all such shifts to S are applied.

Example 1:

Input: S = "abc", shifts = [3,5,9]
Output: "rpl"
Explanation: 
We start with "abc".
After shifting the first 1 letters of S by 3, we have "dbc".
After shifting the first 2 letters of S by 5, we have "igc".
After shifting the first 3 letters of S by 9, we have "rpl", the answer.

Note:

  1. 1 <= S.length = shifts.length <= 20000
  2. 0 <= shifts[i] <= 10 ^ 9

 

這道題讓我們對字母進行漂移,給了一個 shifts 數組,里面是對應對需要漂移值,但是需要注意的是,shifts[i] 表示對於原字符串 [0, i] 范圍內的所有的字符都進行 shifts[i] 的漂移,那么實際上第一個字母其實把 shifts 數組所有的數字都漂移了一遍,而第二個字母則是把 shifts 數組從第二個數字開始到最后的所有數字都漂移了,而最后一個字母就只漂移了最后一個數字。這不就是一個反向累加和數組么,只要建立了反向累加和數組,那么每個位子上的數字就是對應的字母的漂移值了。為了節省空間,我們就不另建數組了,直接在 shifts 數組上累加就行了,注意累加值要對 26 取余,因為累加和數組可能會整型溢出,取余后就不會有這個問題,而且由於字母漂移 2 6次后,都會回到原來的位置,所以對 26 取余並不會影響到最后的結果。

反向累加和數組建立好了之后,就要開始對字母進行漂移了,這里還有個需要注意的地方,不能直接用原字母加上漂移值,因為一旦超過了 'z' 的時候,是需要從 'a' 重新的開始的,為了處理所有的情況,可以使用一個很常用的 trick,就是先算出字母到 'a' 之間的距離,然后加上漂移值,再對 26 取余,這就是漂移后與 'a' 的距離了,再加上 'a' 變成字母即可,參見代碼如下:

 

class Solution {
public:
    string shiftingLetters(string S, vector<int>& shifts) {
        for (int i = (int)shifts.size() - 2; i >= 0; --i) {
            shifts[i] = (shifts[i] + shifts[i + 1]) % 26;
        }
        for (int i = 0; i < shifts.size(); ++i) {
            S[i] = (S[i] - 'a' + shifts[i]) % 26 + 'a';
        }
        return S;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/848

 

參考資料:

https://leetcode.com/problems/shifting-letters/

https://leetcode.com/problems/shifting-letters/discuss/137906/C%2B%2BJavaPython-Easy-Understood

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM