mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
更新 0541.反转字符串II.md python部分,去除自造轮子部分,优化代码可读性
维持原方法的思路,简化了包和匿名函数的用法 原代码使用了reduce包 + 匿名函数来实现 ''.join的操作,去除该部分提升运行效率
This commit is contained in:
@ -155,34 +155,27 @@ class Solution {
|
||||
|
||||
Python:
|
||||
```python
|
||||
|
||||
class Solution(object):
|
||||
def reverseStr(self, s, k):
|
||||
class Solution:
|
||||
def reverseStr(self, s: str, k: int) -> str:
|
||||
"""
|
||||
:type s: str
|
||||
:type k: int
|
||||
:rtype: str
|
||||
1. 使用range(start, end, step)来确定需要调换的初始位置
|
||||
2. 对于字符串s = 'abc',如果使用s[0:999] ===> 'abc'。字符串末尾如果超过最大长度,则会返回至字符串最后一个值,这个特性可以避免一些边界条件的处理。
|
||||
3. 用切片整体替换,而不是一个个替换.
|
||||
"""
|
||||
from functools import reduce
|
||||
# turn s into a list
|
||||
s = list(s)
|
||||
|
||||
# another way to simply use a[::-1], but i feel this is easier to understand
|
||||
def reverse(s):
|
||||
left, right = 0, len(s) - 1
|
||||
def reverse_substring(text):
|
||||
left, right = 0, len(text) - 1
|
||||
while left < right:
|
||||
s[left], s[right] = s[right], s[left]
|
||||
text[left], text[right] = text[right], text[left]
|
||||
left += 1
|
||||
right -= 1
|
||||
return s
|
||||
return text
|
||||
|
||||
# make sure we reverse each 2k elements
|
||||
for i in range(0, len(s), 2*k):
|
||||
s[i:(i+k)] = reverse(s[i:(i+k)])
|
||||
res = list(s)
|
||||
|
||||
# combine list into str.
|
||||
return reduce(lambda a, b: a+b, s)
|
||||
for cur in range(0, len(s), 2 * k):
|
||||
res[cur: cur + k] = reverse_substring(res[cur: cur + k])
|
||||
|
||||
return ''.join(res)
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user