Update 剑指Offer58-II.左旋转字符串.md

This commit is contained in:
jianghongcheng
2023-05-06 17:52:08 -05:00
committed by GitHub
parent 515c135d61
commit 7cfd389402

View File

@ -142,15 +142,16 @@ class Solution {
``` ```
python: python:
(版本一)使用切片
```python ```python
# 方法一:可以使用切片方法
class Solution: class Solution:
def reverseLeftWords(self, s: str, n: int) -> str: def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:] + s[0:n] return s[n:] + s[:n]
``` ```
版本二使用reversed + join
```python ```python
# 方法二:也可以使用上文描述的方法,有些面试中不允许使用切片,那就使用上文作者提到的方法
class Solution: class Solution:
def reverseLeftWords(self, s: str, n: int) -> str: def reverseLeftWords(self, s: str, n: int) -> str:
s = list(s) s = list(s)
@ -161,32 +162,29 @@ class Solution:
return "".join(s) return "".join(s)
``` ```
版本三自定义reversed函数
```python ```python
# 方法三如果连reversed也不让使用那么自己手写一个
class Solution: class Solution:
def reverseLeftWords(self, s: str, n: int) -> str: def reverseLeftWords(self, s: str, n: int) -> str:
def reverse_sub(lst, left, right): s_list = list(s)
while left < right:
lst[left], lst[right] = lst[right], lst[left]
left += 1
right -= 1
res = list(s) self.reverse(s_list, 0, n - 1)
end = len(res) - 1 self.reverse(s_list, n, len(s_list) - 1)
reverse_sub(res, 0, n - 1) self.reverse(s_list, 0, len(s_list) - 1)
reverse_sub(res, n, end)
reverse_sub(res, 0, end)
return ''.join(res)
# 同方法二 return ''.join(s_list)
# 时间复杂度O(n)
# 空间复杂度O(n)python的string为不可变需要开辟同样大小的list空间来修改 def reverse(self, s, start, end):
while start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
``` ```
(版本四)使用 模 +下标
```python 3 ```python 3
#方法四:考虑不能用切片的情况下,利用模+下标实现
class Solution: class Solution:
def reverseLeftWords(self, s: str, n: int) -> str: def reverseLeftWords(self, s: str, n: int) -> str:
new_s = '' new_s = ''
@ -196,17 +194,21 @@ class Solution:
return new_s return new_s
``` ```
(版本五)使用 模 + 切片
```python 3 ```python 3
# 方法五:另类的切片方法
class Solution: class Solution:
def reverseLeftWords(self, s: str, n: int) -> str: def reverseLeftWords(self, s: str, n: int) -> str:
n = len(s) l = len(s)
s = s + s # 复制输入字符串与它自己连接
return s[k : n+k] s = s + s
# 计算旋转字符串的起始索引
k = n % (l * 2)
# 从连接的字符串中提取旋转后的字符串并返回
return s[k : k + l]
# 时间复杂度O(n)
# 空间复杂度O(n)
``` ```
Go Go