ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
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. 给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。 Example: ``` Input: s = "abcdefg", k = 2 Output: "bacdfeg" ``` Restrictions: * The string consists of lower English letters only. * Length of the given string and k will in the range [1, 10000] ``` 思路:先将字符串分片(每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; }; ```