Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

344. 反转字符串 #36

Open
Geekhyt opened this issue Feb 22, 2021 · 0 comments
Open

344. 反转字符串 #36

Geekhyt opened this issue Feb 22, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 22, 2021

原题链接

先明确题目要求:

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

const reverseString = function(s) {
    s.reverse()
}

这道题可不是为了考察我们是否知道 reverse() 这个 API,我们来看不借助内置方法如何解题。

双指针

  1. 借助双指针left、right分别指向头尾。
  2. 两个指针不断夹逼,进行交换位置完成反转。
const reverseString = function (s) {
    let left = 0, right = s.length - 1;
    while (left < right) {
        [s[left], s[right]] = [s[right], s[left]]
        left++
        right--
    }
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
@Geekhyt Geekhyt added the 简单 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant