旋转字符串
- 问题描述
给定一个字符串(以字符数组的形式)和一个偏移量,根据偏移量原地从左向右旋转字符串。
2.问题实例
输入str = “abcdefg”,offset=3,输出“efgabcd”。
输入str = “abcdefg”,offset=0,输出“abcdefg”。
输入str = “abcdefg”,offset=1,输出“gabcdef”。
3.代码实现
class Solution:
#参数s:字符列表
#参数offset:整数
#返回值:无
def rotateString(self,s,offset):
if len(s)>0:
offset = offset % len(s)
temp = (s + s)[len(s) - offset:2 * len(s) - offset]
for i in range(len(temp)):
s[i] = temp[i]
#主函数
if __name__ == '__main__':
s = ["a","b","c","d","e","f","g"]
offset = 3
solution = Solution()
solution.rotateString(s,offset)
print("输入:s=",["a","b","c","d","e","f","g"],"\n\t","offset = ",offset)
print("输出:s=",s)
对主函数进行调整:
if __name__ =='__main__':
solution = Solution()
s=list(input("输入:s="))
offset = int(input("offset="))
solution.rotateString(s,offset)
print("输出:s=", s)
示例: