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:

  1. Input: s = "abcdefg", k = 2
  2. Output: "bacdfeg"

Solution:

  1. /**
  2. * @param {string} s
  3. * @param {number} k
  4. * @return {string}
  5. */
  6. var reverseStr = function(s, k) {
  7. const arr = s.split('');
  8. for (let i = 0; i < arr.length; i += k * 2) {
  9. let j = Math.min(arr.length - 1, i + k - 1);
  10. for (let m = i, n = j; m < n; m++, n--) {
  11. let t = arr[m];
  12. arr[m] = arr[n];
  13. arr[n] = t;
  14. }
  15. }
  16. return arr.join('');
  17. };

Runtime: 80 ms, faster than 27.78% of JavaScript online submissions for Reverse String II.