From 857ce0f8f5f5d5201c7ec16d74d6f4fa806f30c0 Mon Sep 17 00:00:00 2001 From: tw2665 <55668073+tw2665@users.noreply.github.com> Date: Thu, 20 May 2021 16:52:58 -0400 Subject: [PATCH] add python solution to 0541.reverseStrII --- problems/0541.反转字符串II.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 0a92ac8b..75ac39b0 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -134,6 +134,36 @@ class Solution { ``` Python: +```python3 + +class Solution(object): + def reverseStr(self, s, k): + """ + :type s: str + :type k: int + :rtype: str + """ + 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 + while left < right: + s[left], s[right] = s[right], s[left] + left += 1 + right -= 1 + return s + + # 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) + +``` Go: