題目:
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;
}