给定一个字符串str和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。
对于不同的语言,str将以不用的形式给出,例如对于字符串 “abc” ,将以下面的形式给出
Java: char[] str = {‘a’, ‘b’, ‘c’};
Python:str = [‘a’, ‘b’, ‘c’]
C++:string str = “abc”;
样例
样例 1:
输入:str = "abcdefg" offset = 3
输出:"efgabcd"
解释:注意是原地旋转,即str旋转后为"efgabcd"
样例 2:
输入:str = "abcdefg" offset = 0
输出:"abcdefg"
解释:注意是原地旋转,即str旋转后为"gabcdef"
样例 3:
输入:str = "abcdefg" offset = 1
输出:"gabcdef"
解释:注意是原地旋转,即str旋转后为"gabcdef"
样例 4:
输入:str = "abcdefg" offset = 2
输出:"fgabcde"
解释:注意是原地旋转,即str旋转后为"fgabcde"
样例 5:
输入:str = "abcdefg" offset = 10
输出:"efgabcd"
解释:注意是原地旋转,即str旋转后为"efgabcd"
思路:
切片,答案=逆置(逆置+逆置)
代码:
from typing import (
List,
)
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str: List[str], offset: int):
# write your code here
if len(str) > 0:
offset = offset % len(str)
M = offset
str[:-M] = str[:-M][::-1]
print(str)
str[-M:] = str[-M:][::-1]
print(str)
str[:] = str[:][::-1]