Skip to content

Commit

Permalink
Merge pull request youngyangyang04#218 from tw2665/patch-4
Browse files Browse the repository at this point in the history
add python solution to 0541.reverseStrII
  • Loading branch information
youngyangyang04 authored May 23, 2021
2 parents dcd39c7 + 5fe52a5 commit f582c2e
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions problems/0541.反转字符串II.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,36 @@ class Solution {
```

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:
Expand Down

0 comments on commit f582c2e

Please sign in to comment.