- 左旋转字符串
- 1.两种解法
- 第一种—使用辅助空间
- 第二种—不使用辅助空间
- 2.总结
- python
- 算法
leetcode链接
1.两种解法 第一种—使用辅助空间具体步骤是:
将前n个字符保存在一个新字符串中,然后把原字符串的[n,len(s))子串与新字符串拼接起来即可
def reverseLeftWords(s,n): new_s = s[:n] s = s[n:]+new_s return s第二种—不使用辅助空间
如果不使用辅助空间,只在原字符串上操作,需要使用局部反转+整体反转的思想
具体步骤为:
- 反转区间为前n的子串
- 反转区间为n到末尾的子串
- 反转整个字符串
代码如下:
def reverseLeftWords(s,n):
def reversestr(s):
left, right = 0, len(s)-1
while left
2.总结
python
- 当容器作为函数参数时,对参数的修改也会导致原容器被修改,这是一种浅拷贝
算法
- 掌握局部反转+全局反转的思想



