541. Reverse String II

202410202129
tags: #string #two-pointers

const swap = (arr, start, end) => {
	while (start < end) {
		[arr[start], arr[end]] = [arr[end], arr[start]];
		start += 1;
		end -= 1;
	}
}

var reverseStr = function(s, k) {
	const arr = s.split('');
	for (let i = 0; i < arr.length; i += k * 2) {
		swap(arr, i, Math.min(i + k - 1, arr.length - 1));
	}
	return arr.join('');
};

Reference

https://leetcode.com/problems/reverse-string-ii/