From 6255eae04cefc676d243bc53ea4070bc900b3c99 Mon Sep 17 00:00:00 2001 From: Eyjan_Huang <81480748+Eyjan-Huang@users.noreply.github.com> Date: Thu, 19 Aug 2021 21:01:20 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A1=A5=E5=85=85=20=E5=89=91=E6=8C=87Offer58-?= =?UTF-8?q?II.=E5=B7=A6=E6=97=8B=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2.md=20?= =?UTF-8?q?python=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 如果不让使用自带函数reversed() 可以使用该方法 --- problems/剑指Offer58-II.左旋转字符串.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index 1073dafa..6070f85b 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -136,13 +136,28 @@ class Solution: # return "".join(s) +# 方法三:如果连reversed也不让使用,那么自己手写一个 +class Solution: + def reverseLeftWords(self, s: str, n: int) -> str: + def reverse_sub(lst, left, right): + while left < right: + lst[left], lst[right] = lst[right], lst[left] + left += 1 + right -= 1 + + res = list(s) + end = len(res) - 1 + reverse_sub(res, 0, n - 1) + reverse_sub(res, n, end) + reverse_sub(res, 0, end) + return ''.join(res) # 时间复杂度:O(n) # 空间复杂度:O(n),python的string为不可变,需要开辟同样大小的list空间来修改 ``` ```python 3 -#方法三:考虑不能用切片的情况下,利用模+下标实现 +#方法四:考虑不能用切片的情况下,利用模+下标实现 class Solution: def reverseLeftWords(self, s: str, n: int) -> str: new_s = ''