From e6571ecaac55a91a557b32248560ef5fac612cf1 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Thu, 19 Aug 2021 17:30:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=200541.=E5=8F=8D=E8=BD=AC?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2II.md=20python=E9=83=A8=E5=88=86?= =?UTF-8?q?=EF=BC=8C=E5=8E=BB=E9=99=A4=E8=87=AA=E9=80=A0=E8=BD=AE=E5=AD=90?= =?UTF-8?q?=E9=83=A8=E5=88=86=EF=BC=8C=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E5=8F=AF=E8=AF=BB=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 维持原方法的思路,简化了包和匿名函数的用法 原代码使用了reduce包 + 匿名函数来实现 ''.join的操作,去除该部分提升运行效率 --- problems/0541.反转字符串II.md | 35 ++++++++++++------------------ 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index ab1ef16a..02713c65 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -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)]) - - # combine list into str. - return reduce(lambda a, b: a+b, s) + res = list(s) + + for cur in range(0, len(s), 2 * k): + res[cur: cur + k] = reverse_substring(res[cur: cur + k]) + return ''.join(res) ```