题解 | #反转字符串#
反转字符串
https://www.nowcoder.com/practice/c3a6afee325e472386a1c4eb1ef987f3
/** * 反转字符串 * @param str string字符串 * @return string字符串 */ function solve(str) { // write code here // 1. 直接for循环从尾到头 // 2. 双指针,头尾对换 let len = parseInt(str.length / 2); let s; let strArr = [...str]; for (let i = 0; i < len; i++) { let j = strArr.length - 1 - i; s = strArr[i]; strArr[i] = strArr[j]; strArr[j] = s; //console.log(str) } //更巧妙 // let left = 0; // let right = str.length - 1; // let strArr = [...str]; // while (left < right) // [strArr[left++], strArr[right--]] = [strArr[right], strArr[left]]; return strArr.join(""); //一行代码 //var arr = str.split('').reverse().join(''); //return arr } module.exports = { solve: solve, };
牛客算法题 文章被收录于专栏
牛客算法题记录