LeetCode 541. Reverse String II (Javascript solution)
codingpineapple
Posted on August 7, 2020
Description:
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 left the other as original.
var reverseStr = function(s, k) {
// strings are immutable in javascript
// converting to an array will allow in place letter swapping
const a = s.split('');
// loop through the array in 2*k increments
for (let start = 0; start < a.length; start += 2 * k) {
let i = start;
let j = Math.min(start + k - 1, a.length - 1);
// reverse first k characters in current increment
while (i < j) {
let tmp = a[i];
a[i++] = a[j];
a[j--] = tmp;
}
}
// return a string as the result
return a.join('');
};
π πͺ π
π©
codingpineapple
Posted on August 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
sorting Recap the highlight of the sorting algorithms using JavaScript for beginners
October 5, 2024
datastructures DSA with JS: Understanding Custom Array Data Structure in JavaScript - A Step-by-Step Guide
September 29, 2024