LeetCode 848. Shifting Letters

原题链接在这里:https://leetcode.com/problems/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

题解:

First calculate how many steps should each char stift by accumlating the number from n-1 to 0.

Then, shift char by the corresponding step. 

If it already past 'z', minus by 26.

Time Complexity: O(n). n = shifts.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public String shiftingLetters(String S, int[] shifts) {
 3         if(S == null || S.length() == 0){
 4             return S;
 5         }
 6         
 7         int n = shifts.length;
 8         int sum = 0;
 9         for(int i = n-1; i>=0; i--){
10             sum = (sum+shifts[i])%26;
11             shifts[i] = sum;
12         }
13         
14         char [] arr = S.toCharArray();
15         for(int i = 0; i<n; i++){
16             arr[i] += shifts[i];
17             if(arr[i] > 'z'){
18                 arr[i] -= 26;
19             }
20         }
21         
22         return new String(arr);
23     }
24 }

类似Group Shifted Strings.

posted @ 2019-12-03 11:04  Dylan_Java_NYC  阅读(243)  评论(0编辑  收藏  举报