Skip to content

Commit 2b30979

Browse files
committedDec 12, 2020
feat: reverse-string-ii
1 parent 2de6782 commit 2b30979

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
 

‎str.reverse-string-ii.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution:
2+
"""
3+
541. 反转字符串 II
4+
https://leetcode-cn.com/problems/reverse-string-ii/
5+
给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。
6+
如果剩余字符少于 k 个,则将剩余字符全部反转。
7+
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
8+
"""
9+
def reverseStr(self, s: str, k: int) -> str:
10+
arr = list(s)
11+
for i in range(0, len(arr), 2 * k):
12+
arr[i:i+k] = reversed(arr[i:i+k])
13+
14+
return ''.join(arr)
15+
16+
so = Solution()
17+
print(so.reverseStr('abcd', 3))

0 commit comments

Comments
 (0)
Please sign in to comment.