LeetCode刷题实战541:反转字符串 II
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer 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 leave the other as original.
示例
示例 1:
输入:s = "abcdefg", k = 2
输出:"bacdfeg"
示例 2:
输入:s = "abcd", k = 2
输出:"bacd"
解题
class Solution {
public:
string reverseStr(string s, int k) {
// i 每次移动 2 * k
for (int i = 0; i < s.size(); i = i + 2 * k) {
// left 和 right 定义需要反转的区间
int left = i;
int right;
//判断要交换的区间里面还有没有 k 个元素
if (i + k - 1 >= s.size()) {
right = s.size() - 1;
} else {
right = i + k - 1;
}
//将区间内的元素进行交换
while (left < right) {
int temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
return s;
}
};