题目:
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]
翻译:
给定一个字符串和一个数字k,你需要翻转从字符串开始起每2k的字符的前k的字符。如果剩下的字符少于k个,那么将它们都翻转。如果剩下的字符少于2k但是大于等于k个,那么翻转前k个字符,剩下的保持不变。
例子:
输入: s = "abcdefg", k = 2 输出: "bacdfeg"约束条件:
- 字符串中只包含小写的英文字母。
- 给定的字符串和k的长度在[1,10000]范围内。
思路:
从头开始扫描所有2k的子字符串,根据条件进行判断。
C++代码(Visual studio 2107):
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string reverseStr(string s, int k) {
for (int i = 0; i < s.size(); i += 2 * k) {
if (i + k >= s.size())
reverse(s.begin() + i, s.end());
else
reverse(s.begin() + i, s.begin()+i+k);
}
return s;
}
};
int main()
{
Solution s;
string str = "abcdefg";
int k = 2;
string result = s.reverseStr(str, k);
cout << result<<endl;
return 0;
}