# 541.Reverse String II

**541.Reverse String II**

难度:Easy

> 给定一个字符串和一个整数 k，你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符，则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符，则反转前 k 个字符，并将剩余的字符保持原样。

```
示例:

输入: s = "abcdefg", k = 2
输出: "bacdfeg"
要求:

该字符串只包含小写的英文字母。
给定字符串的长度和 k 在[1, 10000]范围内。
```

可以直接用字符串长度除以k，得到需要进行反转的字符串数目。最后将剩下的字符串加到结果中即可。

```
class Solution {
public:
    string reverseStr(string s, int k) {
        string res;
        int count=s.length()/k;
        for(int i=0;i<count;i++)
        {
            if(i%2) 
            {
                for(int j=0;j<k;j++)
                {
                    res+=s[i*k+j];
                }
            }
            else
            {
                for(int j=k-1;j>=0;j--)
                    res+=s[i*k+j];
            }
        }
        if(count%2)
        for(int i=count*k;i<s.length();i++)
            res+=s[i];
        else
            for(int i=s.length()-1;i>=count*k;i--)
            res+=s[i];
        return res;
    }
};
```

> 执行用时 :12ms, 在所有 C++ 提交中击败了69.60%的用户\
> 内存消耗 :10 MB, 在所有 C++ 提交中击败了21.26%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/541.reverse_string_ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
