1. Description
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 character left, reverse all of them. If there are less than 2k but greater than or eqaul to k characters, then reverse the first k characters and leave the other as original.
constraints :
- 1 <= s.length <= \(10^{4}\)
- s consists of only lowercase English letters.
- 1 <= k <= \(10^{4}\)
2. Algorithms
Let's consider the problem when we got input s as "abcdefghijk" and k as 3. Then we have to reverse the first 3 character s for every 6 characters from the start of the string.
If there are fewer than 3 characters left, we have to reverse all of them. If there are less than 6 but greater than or eqaul to 3 characters, then we have to reverse the first 3 characters and leave other as original.
"abcdef" -> "cbadef"
"ghijk" -> "ihgjk"
- Start
- Convert input string into list.
- Repeat the steps through integers 0 - len(s) incrementing by 2k.
- Reverse the values in index i : i + k
- Return the joined list.
- End
3. Codes
class Solution:
def reverseStr(self, s: str, k: int) -> str:
s = list(s)
for i in range(0, len(s), 2*k) :
s[i:i+k] = s[i:i+k][::-1]
return "".join(s)
4. Conclusion
'LeetCode > Easy' 카테고리의 다른 글
551 Student Attendance Record I (0) | 2022.09.05 |
---|---|
543 Diameter of Binary Tree (0) | 2022.09.05 |
530 Minimum Absolute Difference in BST (0) | 2022.09.05 |
521 Longest Uncommon Subsequence I (0) | 2022.09.04 |
520 Detect Capital (0) | 2022.09.03 |