Day13. Reverse String II(541)

问题描述
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"

思路:先将字符串分片(每2k为一组),然后对每一组进行长度判断,长度小于k的和长度大于k*

/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var reverseStr = function(s, k) { 
    if(k <= 1){
        return s;
    }    
    var Arr = [];
    for(var i = 0 ; i < s.length; i += 2*k ){
        var subStr = s.slice(i,i+2*k);
        var arr = subStr.split('');
        if(arr.length <= k){
          var str =  arr.reverse().join('');
        }else{
            var subArr = arr.slice(0,k);
            subArr.reverse(); 
            var str = subArr.concat(arr.slice(k,2*k)).join('');
        }
        Arr[i] = str;
    }    
    var result = Arr.join('');
    return result;
};
    原文作者:前端伊始
    原文地址: https://www.jianshu.com/p/ca89410fa084
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞