From: https://leetcode.com/
mode: random pick
degree: Medium
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 <= S.length = shifts.length <= 20000
0 <= shifts[i] <= 10 ^ 9
My solution:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # Time : 2018/11/8 4 5 6 class Solution: 7 def __init__(self): 8 self.s_list = [] 9 self.result = [] 10 11 def shiftingLetters(self, S, shifts): 12 """ 13 :type S: str 14 :type shifts: List[int] 15 :rtype: str 16 """ 17 self.s_list = [ord(i) for i in list(S)] 18 19 def temp(x): 20 req = [self.plusIndex(i, x) for i in self.s_list] 21 self.s_list = req 22 map(temp, shifts) 23 self.result = [chr(i) for i in self.s_list] 24 25 def plusIndex(self, index_node, times, length=26, start_index=97, end_index=122): 26 times_y = times % length 27 req_index = times_y + index_node 28 if req_index > end_index: 29 req_index = req_index - end_index + start_index - 1 30 return req_index 31 32 33 if __name__ == '__main__': 34 s = Solution() 35 s.shiftingLetters("dfsr", [1, 3]) 36 print s.result