Question:
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"
Solution:
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var reverseStr = function(s, k) {
const arr = s.split('');
for (let i = 0; i < arr.length; i += k * 2) {
let j = Math.min(arr.length - 1, i + k - 1);
for (let m = i, n = j; m < n; m++, n--) {
let t = arr[m];
arr[m] = arr[n];
arr[n] = t;
}
}
return arr.join('');
};
Runtime: 80 ms, faster than 27.78% of JavaScript online submissions for Reverse String II.