Topic description:
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]
Function to be done:
string reverseStr(string s, int k)
illustrate:
1. This question is easy to do after understanding the meaning of the question. Given a string s and a number k, reverse the k bits of the first 2k bits of the string. For example, abcdefg, k=2, that is, the first two abs in the first four abcd are reversed, and the reversed result is bacd.
When we reach the end of the string, we may not always find exactly 2k bits. So at this time, if there are less than 2k bits but greater than or equal to k bits, reverse the first k bits, and do not change the latter. If less than k bits, reverse all remaining letters.
2. We transform the above conditions and construct the following code (with explanation):
string reverseStr(string s, int k)
{
int i= 0 , s1= s.size(),j,t1;//i is used to record the starting position
char t;//Temporary variable in the reverse process
while (i< s1)
{
if (i+ 2 *k- 1 < s1)//normal case
{
t1 =i+ 2 * k;//Record the position of the next letter after processing 2k letters
j = i+k- 1 ;//To process k letters, j records the end position
while (i< j)//reverse
{
t=s[i];
s[i]=s[j];
s[j]=t;
i++;
j--;
}
i = t1;//i is updated to the next letter position to be processed
}
else if(i+2*k-1>=s1&&i+k-1<s1)//特殊情况,<2k&&>=k
{
j=i+k-1;
while(i<j)
{
t=s[i];
s[i]=s[j];
s[j]=t;
i++;
j--;
}
return s;//After processing this special condition, the processing of the entire string must end
}
else if (i+k- 1 >= s1)//special case, <k
{
j=s1-1;
while(i<j)
{
t=s[i];
s[i]=s[j];
s[j]=t;
i++;
j--;
}
return s;
}
}
return s;//If the string is "abcd", k=2, just use the normal case
}
The above code measured 9ms, beats 96.34% of cpp submissions.