?LeetCode刷題實(shí)戰(zhàn)541:反轉(zhuǎn)字符串 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 每次移動(dòng) 2 * k
????for?(int?i = 0; i < s.size(); i = i + 2?* k) {
????????// left 和 right 定義需要反轉(zhuǎn)的區(qū)間
????????int?left = i;
????????int?right;
????????//判斷要交換的區(qū)間里面還有沒有 k 個(gè)元素
????????if?(i + k - 1?>= s.size()) {
????????????right = s.size() - 1;
????????} else?{
????????????right = i + k - 1;
????????}
????????//將區(qū)間內(nèi)的元素進(jìn)行交換
????????while?(left < right) {
????????????int?temp = s[left];
????????????s[left] = s[right];
????????????s[right] = temp;
????????????left++;
????????????right--;
????????}
????}
????return?s;
}
};
