左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
方法一:
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
lenth=len(s)
res=[]
for i in range(0,lenth):
if i>=n:
res.append(s[i])
for j in range(0,n):
if j<=n:
res.append(s[j])
return "".join(res)
此方法优化后:
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
lenth=len(s)
res=[]
for i in range(n,lenth+n):
res.append(s[i%lenth])
return "".join(res)
方法二:
字符串切片法
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:]+s[:n]