8. 旋转字符串

21 篇文章 0 订阅
11 篇文章 0 订阅

思路

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例
    对于字符串 "abcdefg".
    offset=0 => "abcdefg"
    offset=1 => "gabcdef"
    offset=2 => "fgabcde"
    offset=3 => "efgabcd"

Python

class Solution:
    """
    @param str: An array of char
    @param offset: An integer
    @return: nothing
    """

    def rotateString(self, str, offset):
        # write your code here
        if not offset:
            return
        if not str:
            return
        str_length = len(str)
        offset %= str_length
        for i in range(offset):
            ch = str.pop()
            str.insert(0, ch)


if __name__ == "__main__":
    s = Solution()
    ss = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    s.rotateString(ss, 0)
    s.rotateString(ss, 1)
    s.rotateString(ss, 2)
    s.rotateString(ss, 3)

Go

package main

/**
 * @param str: An array of char
 * @param offset: An integer
 * @return: nothing
 */
func rotateString(str *string, offset int) {
    // write your code here
    strLength := len(*str)
    if strLength == 0 {
        return
    }
    offset %= strLength
    rotateStr := (*str)[strLength-offset:] + (*str)[:strLength-offset]
    *str = rotateStr
}

func main() {
    str, offset := "abcdefg", 1
    rotateString(&str, offset)
    str, offset = "", 10
    rotateString(&str, offset)

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值