Merge pull request #218 from tw2665/patch-4

add python solution to 0541.reverseStrII
This commit is contained in:
Carl Sun
2021-05-23 10:44:23 +08:00
committed by GitHub

View File

@ -134,6 +134,36 @@ class Solution {
``` ```
Python Python
```python
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 Go