思路
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例
对于字符串 "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)
}