Day13. Reverse String II(541)
2017-11-19 本文已影响0人
前端伊始
问题描述
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;
};