---
# System prepended metadata

title: LC 541. Reverse String II
tags: [easy, leedcode, python, c++]

---

# LC 541. Reverse String II

### [Problem link](https://leetcode.com/problems/reverse-string-ii/)

###### tags: `leedcode` `easy` `python` `c++`

Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.

If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> 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:** 

- <code>1 <= s.length <= 10<sup>4</sup></code>
- <code>s</code> consists of only lowercase English letters.
- <code>1 <= k <= 10<sup>4</sup></code>

## Solution 1
#### Python
```python=
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        a = list(s)
        for i in range(0, len(s), 2 * k):
            a[i : i + k] = reversed(a[i : i + k])
        return ''.join(a)
```
#### C++
```cpp=
class Solution {
public:
    string reverseStr(string s, int k) {
        for (int i = 0; i < s.size(); i += 2 * k) {
            if (i + k <= s.size()) {
                reverse(s.begin() + i, s.begin() + i + k);
            } else {
                reverse(s.begin() + i, s.end());
            }
        }
        return s;
    }
};
```

>### Complexity
>|                     | Time Complexity | Space Complexity |
>| ------------------- | --------------- | ---------------- |
>| Solution 1(c++)     | O(n)            | O(1)             |
>| Solution 1(python)  | O(n)            | O(n)             |

## Note
因為python在string沒有像c++這樣方便的reverse function, 所以需要先轉成list, 再用list slice處理, 所以Space Complexity為O(n)