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"
void reverse(int start,int end,char *s)
{
char tmp;
while(start < end)
{
tmp = s[end];
s[end--] = s[start];
s[start++] = tmp;
}
}
char* reverseStr(char* s, int k)
{
/*cal len of s*/
int len = strlen(s);
/*len less than k*/
if(len <= k)
{
reverse(0,len - 1,s);
return s;
}
for (int i = 0; i < len; i += 2 * k)
{ /*at least 2k left*/
if(i + 2*k <=len)
{
reverse(i,i + k - 1,s);
}
/*more than or equal to k left*/
else if(len - i >= k)
{
reverse(i,i + k - 1,s);
break;
}
/*less than k,reverse i to len-1*/
else if(len - i < k)
{
reverse(i,len - 1,s);
break;
}
}
return s;
}