小 白 一 枚 , 努 力 敲 代 码 中 , 请 各 位 大 大 多 多 指 教 小白一枚,努力敲代码中,请各位大大多多指教 小白一枚,努力敲代码中,请各位大大多多指教
1. 题目描述
We have a string
S
S
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
′
'z'
′z′ becomes
′
a
′
'a'
′a′).
For example,
s
h
i
f
t
(
′
a
′
)
=
′
b
′
,
s
h
i
f
t
(
′
t
′
)
=
′
u
′
,
a
n
d
s
h
i
f
t
(
′
z
′
)
=
′
a
′
.
shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
shift(′a′)=′b′,shift(′t′)=′u′,andshift(′z′)=′a′.
Now for each
s
h
i
f
t
s
[
i
]
=
x
shifts[i] = x
shifts[i]=x, we want to shift the first
i
+
1
i+1
i+1 letters of
S
S
S,
x
x
x times.
Return the final string after all such shifts to
S
S
S are applied.
2. 第一次尝试
首先是字母和数字的转化, c h r ( i n t ) chr(int) chr(int)是将数字转化成字母, o r d ( ′ a ′ ) ord('a') ord(′a′)是将字母转化成数字。大写字母是从65到91;小写字母是从97到123;所有数字(个位)是从48到58。
问题:如何实现shifting the first 2/3/… letters?
根据
i
n
d
e
x
index
index可以将第一个,第二个…进行
s
h
i
f
t
shift
shift,但是如何对前
i
i
i个进行操作呢?
解答:
S | a | b | c |
---|---|---|---|
shift | 3+5+9=17 | 5+9=14 | 9 |
ans | r | p | l |
所以我们可以首先计算出来 s h i f t s shifts shifts列表中各个数字之和,然后每循环一次,减去 s h i f t [ i ] shift[i] shift[i]。
注意:计算
s
u
m
sum
sum的时候要取模:sum(shifts)%26
运行成功:答案为
r
p
l
rpl
rpl。
submit:失败!
测试实例为:input: “ruu”;shifts = [26,9,7]。
正确答案应该是
"
r
u
l
"
"rul"
"rul",但是上面的代码执行结果为:“ru�”
原因:
o
r
d
(
′
u
′
)
=
117
ord('u') = 117
ord(′u′)=117,加上7结果为124,但是小写字母的范围是96~123,所以输出为未知符号。
3. 第二次尝试
第一次尝试的错误是没有正确的估计小写字母的范围,所以导致数字超出范围而失败。
第二次尝试,首先算出来每个字母在小写字母中是第几个,然后加上shift的大小,总和要和26取模, 最终转化为小写字母的时候只需要加上97即可。
运行成功!!撒花★,°:.☆( ̄▽ ̄)/$:.°★ 。
4. 总结:
题目中有Note:
- 1 <= S.length = shifts.length <= 20000(不能够使用 n 2 n^2 n2的算法)
- 0 <= shifts[i] <= 10 ^ 9(不注意的话可能会爆掉)
Solution 1:Brute Force
Time complexity:
O
(
n
2
)
O(n^2)
O(n2)
Space complexity:
O
(
1
)
O(1)
O(1)
Solution 2: Prefix-sum
Note部分shift的大小给定了,所以我们不能一直加下去,每一次加完都要和26取模。
Time Complecity:
O
(
N
)
O(N)
O(N)
Space Complexity:
O
(
N
)
O(N)
O(N) the space need to output the answer.