File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
solution/0848.Shifting Letters Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 字母移位
2
+
3
+ ### 问题描述
4
+
5
+ 有一个由小写字母组成的字符串 ` S ` ,和一个整数数组 ` shifts ` 。
6
+
7
+ 我们将字母表中的下一个字母称为原字母的 移位(由于字母表是环绕的, ` 'z' ` 将会变成 ` 'a' ` )。
8
+
9
+ 例如·,` shift('a') = 'b' ` , ` shift('t') = 'u' ` ,, 以及 ` shift('z') = 'a' ` 。
10
+
11
+ 对于每个 ` shifts[i] = x ` , 我们会将 ` S ` 中的前 ` i+1 ` 个字母移位 ` x ` 次。
12
+
13
+ 返回将所有这些移位都应用到 ` S ` 后最终得到的字符串。
14
+
15
+ ** 示例:**
16
+ ```
17
+ 输入:S = "abc", shifts = [3,5,9]
18
+ 输出:"rpl"
19
+ 解释:
20
+ 我们以 "abc" 开始。
21
+ 将 S 中的第 1 个字母移位 3 次后,我们得到 "dbc"。
22
+ 再将 S 中的前 2 个字母移位 5 次后,我们得到 "igc"。
23
+ 最后将 S 中的这 3 个字母移位 9 次后,我们得到答案 "rpl"。
24
+ ```
25
+
26
+ ** 提示:**
27
+ - 1 <= S.length = shifts.length <= 20000
28
+ - 0 <= shifts[ i] <= 10 ^ 9
29
+
30
+ ### 解法
31
+
32
+ 对于` S ` 中的每个字母,先将需要移动的长度求出,然后直接移位即可。从后往前遍历会比从前往后遍历快一点点,因为从前往后需要先求出` shifts ` 的和。
33
+
34
+ ``` python
35
+ class Solution :
36
+ def shiftingLetters (self , S , shifts ):
37
+ mov = 0
38
+ ans = list (S)
39
+ for i in range (len (S) - 1 , - 1 , - 1 ):
40
+ mov += shifts[i]
41
+ ans[i] = chr ((ord (S[i]) - 97 + mov % 26 ) % 26 + 97 )
42
+ return ' ' .join(ans)
43
+
44
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def shiftingLetters (self , S , shifts ):
3
+ """
4
+ :type S: str
5
+ :type shifts: List[int]
6
+ :rtype: str
7
+ """
8
+ mov = 0
9
+ ans = list (S )
10
+ for i in range (len (S ) - 1 , - 1 , - 1 ):
11
+ mov += shifts [i ]
12
+ ans [i ] = chr ((ord (S [i ]) - 97 + mov % 26 ) % 26 + 97 )
13
+ return '' .join (ans )
You can’t perform that action at this time.
0 commit comments