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"
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
思路:
以2*k 为一组,每一组前k个字符翻转,然后处理剩余字符。
写出来感觉好啰嗦。。另外简洁的代码看到大神有用stl的reverse的,回头试一下,省不少事儿。
string reverseStr(string s, int k)
{
int group = s.size()/(*k);
int i = ;
for (; i < group;i++)
{
for (int j = ; j < k/;j++)
{
swap(s[i * * k + j], s[i * * k + k-j-]);
}
}
int remain = s.size() % ( * k);
int end = (remain >= k) ? k : remain ;
for (int j = ; j < end/;j++)
{
swap(s[i * * k + j], s[i * * k + end - j - ]);
}
return s;
}