[编程题] 反转字符串

递归做法

  • pros: 不占用额外空间
  • cons: 输入太长会爆栈
function reverseString(s: string): string {
    if (s === "") {
        return ""
    }
    return reverseString(s.substring(1)) + s.charAt(0)
}

const s = "Hello world"

console.log(reverseString(s)) // "dlrow olleH"

转成数组

  • pros: 清晰易懂
  • cons: 占用额外空间
function reverseString(s: string): string {
    return s.split('').reverse().join('')
}
posted @ 2022-09-12 16:45  toddforsure  阅读(7)  评论(0)    收藏  举报