add python solution to 0541.reverseStrII

This commit is contained in:
tw2665
2021-05-20 16:52:58 -04:00
committed by GitHub
parent 942bd655b6
commit 857ce0f8f5

View File

@ -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