Leetcode-848. Shifting Letters


小 白 一 枚 , 努 力 敲 代 码 中 , 请 各 位 大 大 多 多 指 教 小白一枚,努力敲代码中,请各位大大多多指教

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个进行操作呢?
解答:

Sabc
shift3+5+9=175+9=149
ansrpl

所以我们可以首先计算出来 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. 1 <= S.length = shifts.length <= 20000(不能够使用 n 2 n^2 n2的算法)
  2. 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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值