-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_string_II.py
More file actions
59 lines (48 loc) · 1.57 KB
/
Copy pathreverse_string_II.py
File metadata and controls
59 lines (48 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# 541. Reverse String II
# Easy
# Topics
# conpanies icon
# Companies
# Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
# If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
# Example 1:
# Input: s = "abcdefg", k = 2
# Output: "bacdfeg"
# Example 2:
# Input: s = "abcd", k = 2
# Output: "bacd"
# Constraints:
# 1 <= s.length <= 104
# s consists of only lowercase English letters.
# 1 <= k <= 104
class Solution:
def reverseStr(self, s: str, k: int) -> str:
slist = list(s)
slen = len(slist)
i = 0
j = k - 1
ctr = 0
while j < slen :
while i < j :
slist[i], slist[j] = slist[j], slist[i]
i += 1
j -= 1
ctr += 2
i = (ctr) * k
j = i + k - 1
if slen - i < k :
j = slen - 1
while i < j :
slist[i], slist[j] = slist[j], slist[i]
i += 1
j -= 1
return "".join(slist)
s = Solution()
test_strs = [
["abcdefgh", 2 , "bacdfeg"] ,
["abcdefg", 3, "cbadefg"] ,
["abcdijklpqrstuvwzonezone", 4, "dcbaijklsrqptuvwenozzone" ] ,
["abcdefg", 8, "gfedcba"]
]
for t in test_strs :
print(f'input str : {t[0]}, k : {t[1]}, result : {s.reverseStr(t[0], t[1])}, expected : {t[2]}')