Javascript solution using recursion with explanation.

  • 0
    // A function that reverses the string.
    String.prototype.reverse = function() {
        return this.split("").reverse().join("");
    var reverseStr = function(s, k) {
        var len = s.length;
        if (len < 2*k) { // Check if length is less than 2*k
            if (len >= k)
                // reverse the first k chars and leave the rest as orig
                return s.slice(0, k).reverse() + s.slice(k) 
            else return s.reverse(); // if less than k, return orig
        return s.slice(0, k).reverse() + // reverse first k chars
               s.slice(k, 2*k) + // leave chars from k to 2k as orig
               reverseStr(s.slice(2*k), k); // recurs

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.