ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

(Medium) Shifting Letters - LeetCode

2019-09-03 14:03:16  阅读:294  来源: 互联网

标签:tmp Medium Letters int shift shifts length Shifting letters


Description:

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 S, x 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
Accepted 15,306 Submissions 36,610

 

Solution:

class Solution {
    public String shiftingLetters(String S, int[] shifts) {
      if(S==null||S.length()==0){
          return null;
      }
    if(shifts==null||shifts.length==0){
        return S;
    }
        String res= "";
       
       for(int i = 0; i< shifts.length; i++){
           
           long times = GetTimes(shifts, i);
           
           res = res + Shift(S.charAt(i),times);
       } 
         String sub = S.substring(shifts.length, S.length());
        
        // System.out.println(Shift('m',505870226%26));
        
        return res;
    }
    //97 to 122
    static long GetTimes(int[] arr, int k ){
        long sum = 0;
        for (int i = k; i<arr.length; i++){
            sum = sum + arr[i];
        }
        return sum ; 
    }
    static Character Shift(char a,long k ){
        char tmp = a; 
        k = k%26;
        while (k >0){
         
          if(tmp =='z'){
              tmp = 'a';
          }
            else{
                
               tmp=  (char) ((int)tmp+1);
            }
            
            
            k=k-1;
            
            
        }
        return tmp;
         
    }
}

 

标签:tmp,Medium,Letters,int,shift,shifts,length,Shifting,letters
来源: https://www.cnblogs.com/codingyangmao/p/11452579.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有