Skip to content

Commit 7cfd389

Browse files
Update 剑指Offer58-II.左旋转字符串.md
1 parent 515c135 commit 7cfd389

File tree

1 file changed

+28
-26
lines changed

1 file changed

+28
-26
lines changed

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

+28-26
Original file line numberDiff line numberDiff line change
@@ -142,15 +142,16 @@ class Solution {
142142
```
143143

144144
python:
145+
(版本一)使用切片
145146

146147
```python
147-
# 方法一:可以使用切片方法
148148
class Solution:
149149
def reverseLeftWords(self, s: str, n: int) -> str:
150-
return s[n:] + s[0:n]
150+
return s[n:] + s[:n]
151151
```
152+
(版本二)使用reversed + join
153+
152154
```python
153-
# 方法二:也可以使用上文描述的方法,有些面试中不允许使用切片,那就使用上文作者提到的方法
154155
class Solution:
155156
def reverseLeftWords(self, s: str, n: int) -> str:
156157
s = list(s)
@@ -161,32 +162,29 @@ class Solution:
161162
return "".join(s)
162163

163164
```
165+
(版本三)自定义reversed函数
164166

165167
```python
166-
# 方法三:如果连reversed也不让使用,那么自己手写一个
167168
class Solution:
168-
def reverseLeftWords(self, s: str, n: int) -> str:
169-
def reverse_sub(lst, left, right):
170-
while left < right:
171-
lst[left], lst[right] = lst[right], lst[left]
172-
left += 1
173-
right -= 1
169+
def reverseLeftWords(self, s: str, n: int) -> str:
170+
s_list = list(s)
174171

175-
res = list(s)
176-
end = len(res) - 1
177-
reverse_sub(res, 0, n - 1)
178-
reverse_sub(res, n, end)
179-
reverse_sub(res, 0, end)
180-
return ''.join(res)
172+
self.reverse(s_list, 0, n - 1)
173+
self.reverse(s_list, n, len(s_list) - 1)
174+
self.reverse(s_list, 0, len(s_list) - 1)
181175

182-
# 同方法二
183-
# 时间复杂度:O(n)
184-
# 空间复杂度:O(n),python的string为不可变,需要开辟同样大小的list空间来修改
176+
return ''.join(s_list)
177+
178+
def reverse(self, s, start, end):
179+
while start < end:
180+
s[start], s[end] = s[end], s[start]
181+
start += 1
182+
end -= 1
185183

186184
```
185+
(版本四)使用 模 +下标
187186

188187
```python 3
189-
#方法四:考虑不能用切片的情况下,利用模+下标实现
190188
class Solution:
191189
def reverseLeftWords(self, s: str, n: int) -> str:
192190
new_s = ''
@@ -196,17 +194,21 @@ class Solution:
196194
return new_s
197195

198196
```
197+
(版本五)使用 模 + 切片
199198

200199
```python 3
201-
# 方法五:另类的切片方法
202200
class Solution:
203201
def reverseLeftWords(self, s: str, n: int) -> str:
204-
n = len(s)
205-
s = s + s
206-
return s[k : n+k]
202+
l = len(s)
203+
# 复制输入字符串与它自己连接
204+
s = s + s
205+
206+
# 计算旋转字符串的起始索引
207+
k = n % (l * 2)
208+
209+
# 从连接的字符串中提取旋转后的字符串并返回
210+
return s[k : k + l]
207211

208-
# 时间复杂度:O(n)
209-
# 空间复杂度:O(n)
210212
```
211213

212214
Go:

0 commit comments

Comments
 (0)