题目:
代码(首刷自解 2024年1月16日):
class Solution {
public:void reverse(string& s,int left,int right) {char temp;while (left < right) {temp = s[left];s[left] = s[right];s[right] = temp;++left;--right;}return;}string reverseStr(string s, int k) {int n = s.size();int count = 0;for (int i = 0; i < n; ++i) {++count;if(count == 2 * k){int left = (i + 1) - 2 * k, right = (i + 1) - k - 1;reverse(s,left,right);count = 0;} else if (i == n - 1 && count < k) {int left = (i + 1) - count, right = i;reverse(s,left,right);} else if (i == n - 1 && count >= k && count < 2 * k) {int left = (i + 1) - count, right = (i + 1) - count + k - 1;reverse(s,left,right);}}return s;}
};