美文网首页
旋转字符串 (lintcode:rotate-string)

旋转字符串 (lintcode:rotate-string)

作者: v1coder | 来源:发表于2018-01-02 13:28 被阅读0次

旋转字符串

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

例如:

对于字符串 "abcdefg".
offset=0 => "abcdefg"
offset=1 => "gabcdef"

代码

#第一种方法我自己写的,在Spyder上运行正确,lintcode通不过
def rotateString(str1, offset):
        offset = offset % len(str1) #如果offset大于字符串长度,
        str2 = str1[-offset:]
        str3 = str1[:-offset]
        str4 = str2 + str3
        return str4
    

#第二种方法是网上找的答案,lintcode通过,Spyder上运行报错
def rotateString(s, offset):
    if len(s) > 0:
        offset = offset % len(s)
            
    str2 = (s + s)[len(s) - offset : 2 * len(s) - offset]

    for i in xrange(len(str2)):
        s[i] = str2[i]  # 这里lintcode能通过,可在Spyder上运行报错:'str' object does not support item assignment    

lintcode原题

20180102

相关文章

  • 旋转字符串 (lintcode:rotate-string)

    旋转字符串 给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转) 例如: 对于字符串 "abcdefg...

  • lintCode题解(8)

    标签(空格分隔): lintCode 旋转字符串 给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)...

  • lintcode 旋转字符串

    给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)题目比较简单,只要注意处理一下旋转的个数大于字符串...

  • LintCode - 旋转字符串(普通)

    版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:容易 要求: 给定一个字符串和一个偏移量,根据偏移量旋...

  • LintCode 旋转链表

    题目 给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数 样例给出链表1->2->3->4-...

  • LintCode算法刷题之旋转字符串

    链接:旋转字符串 描述 给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转...

  • LintCode - 旋转链表(中等)

    版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:中等 要求: 给定一个链表,旋转链表,使得每个节点向右...

  • [leetcode/lintcode 题解] 解码字符串 ·

    leetcode/lintcode 题解] 解码字符串 · Decode String 【题目描述】 给出一个表...

  • 796. Rotate String

    题目地址:https://leetcode.com/problems/rotate-string/descript...

  • 旋转字符串

    旋转字符串

网友评论

      本文标题:旋转字符串 (lintcode:rotate-string)

      本文链接:https://www.haomeiwen.com/subject/mbbfnxtx.html