mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Merge pull request #218 from tw2665/patch-4
add python solution to 0541.reverseStrII
This commit is contained in:
@ -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:
|
||||
|
Reference in New Issue
Block a user