1 Star 1 Fork 1

jiniaochi/fe-handwriting

forked from 晴转阴/fe-handwriting 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
33.reverse-string.js 1009 Bytes
一键复制 编辑 原始数据 按行查看 历史
墨惜 提交于 2021-08-07 22:55 . feat: 反转字符串
// 反转字符串 https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnhbqj/
/**
*
*/
// 双指针
const reverseString = (s) => {
let i = 0
let j = s.length - 1
while (i < j) {
let temp = s[ i ]
s[ i ] = s[ j ]
console.log(i, j, temp, s[ j ], s[ i ])
s[ j ] = temp
i++
j--
}
return s
}
// 单指针,做对称交换
const reverseString2 = (s) => {
const len = s.length
const halfLen = len / 2
let i = 0
while (i < halfLen) {
const temp = s[ i ]
const tail = len - 1 - i
s[ i ] = s[ tail ]
s[ tail ] = temp
i++
}
return s
}
// 结构交换两个值
const reverseString3 = (s) => {
const len = s.length
for (let left = 0, right = len - 1; left < right; left++, right--) {
[ s[ right ], s[ left ] ] = [ s[ left ], s[ right ] ]
}
return s
}
console.log(reverseString(["h","e","l","l","o"]))
console.log(reverseString2(["h","e","l","l","o"]))
console.log(reverseString3(["h","e","l","l","o"]))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/jiniaochi/fe-handwriting.git
git@gitee.com:jiniaochi/fe-handwriting.git
jiniaochi
fe-handwriting
fe-handwriting
master

搜索帮助