LeetCode 541 reverse string 2
#include <string>
using namespace std;
class Solution {
public:
string reverseStr(string s, int k) {
int i = 0;
while (i < s.length())
{
if (i+ k > s.length())//剩下的字符串长度小于k的情况
{
k = s.length() - i;
}
string halfStr = s.substr(i, k);//取每2k的前k个字符为子串
reverse(halfStr.begin(), halfStr.end());//翻转字符串
s.replace(i, k, halfStr);//替换这个k长度的子串
i += 2 * k;
}
return s;
}
};