题目:
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.
给定一个字符串和一个整数k,你需要反转从字符串开始计数的每2k个字符的前k个字符。 如果剩余少于k个字符,则将所有字符都反转。 如果小于2k但大于或等于k个字符,则反转前k个字符,并将另一个作为原始字符。
Example:
Input: s = “abcdefg”, k = 2
Output: “bacdfeg”
输入:s =“abcdefg”,k = 2
输出:“bacdfeg”
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
限制:
字符串只包含较低的英文字母。
给定字符串和k的长度将在范围[1,10000]
解答:
直接给出我的答案:9ms
class Solution {
public:
string reverseStr(string s, int k) {
string m = s;//创建一个一样的字符串,修改的时候直接m[a]=s[b];比较方便
int a = 2 * k;//以2k为一个周期,改的时候改半个周期
int d = s.length();//以后还会多次用到,最好先保存一下
for (int i = 0; i < d; i++)
{
int b = i%a;
int c = i - b;
int e = 2 * c + k - 1 - i;//需要交换的元素
if (b < k&&e<d)
{
m[i]= s[e];//不需要swap就可以“交换”元素值
}
}
//只有上面的运算后答案有可能是不对的,比如
//输入:12345678 3
//输出:32145678,不符合题目要求应输出:32145687
int f=d%a;//余数,注意是对2k的,其值可能大于k
int g = d - f;
if (f<k)
{
for (int j = 0; j < f; j++)
{
m[g + j] = s[g + f -1 - j];
}
}
return m;
}
};
总结:
是个简单题,但要求计算不能出错,细心度还是要有的,写的时候出了很多次错,以后要加油啊~~