python & LintCode算法练习:旋转字符串(Rotate String)
程序员文章站
2022-07-16 11:56:59
...
题目详情
https://www.lintcode.com/problem/rotate-string/description
解法
#2019.11.16更新
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, s, offset):
# write your code here
#以rotateString("abcdefg", 3)为例
#PS:虽然s输入是字符串格式,但是不知道为啥在LintCode里变成了列表,我不是很懂
#s=["a","b","c","d","e","f","g"]
if len(s) == 0:#如果字符串为"",直接返回
return s
len_str = len(s)#记录初始字符串的长度
offset = offset % len_str#计算要截取几位末尾字母
s[:] = s * 2
#["a","b","c","d","e","f","g"]->["a","b","c","d","e","f","g","a","b","c","d","e","f","g"]
s[:] = s[len_str-offset:2*len_str-offset]
#可以直接对s切片返回s
return s
#输出结果:"efgabcd"
#虽然s是个列表,但是输出就变成了字符串,不是很懂
结果
Output:
“efgabcd”
Expected:
“efgabcd”
成绩
我提交了几次成绩,每次都不大一样,范围在13%~78%之间,所以成绩多少还要看运气,也有可能是公司的无线不稳定
最新的成绩是96%(2019.11/16更新)
总结
1、之前以为这个题目只能对s自身操作,对s赋值无效。现在听说可以用“s[:]=某列表变量”赋值,试了一下是对的(2019.11.16更新)
2、不知道为什么输入s的是字符串类型,输出也是字符串类型,但是在函数里是列表类型