Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less 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 left the other as original.
Example:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
分析:
给定一个字符串,每隔2k个字符反转其前k个字符。若小于k个字符,则反转所有字符;若小于2k但大于等于k个字符,反转前k个字符。定义变量i记录反转的首位置,根据所给字符串的长度,利用reverse函数反转相应长度字符串即可。
class Solution {
public:
string reverseStr(string s, int k) {
int len = s.size();
int i = 0;
while(i < len)
{
if(i+k < len)
reverse(s.begin()+i , s.begin()+i+k);
else
reverse(s.begin()+i, s.end());
i += k*2;
}
return s;
}
};