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

125. 验证回文串 #35

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

125. 验证回文串 #35

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

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 22, 2021

原题链接

双指针

先明确题意,题目要求只考虑字母和数字字符,并且可以忽略大小写。

1.首先用正则去掉字符串中不是字母和数字的元素,并且都转换成小写。
2.借助双指针 left, right 进行夹逼比较。
3.如果 s[left] 和 s[right] 每一项都相等,则是回文串,否则就不是回文串。

const isPalindrome = function (s) {
    s = s.replace(/[^0-9a-zA-Z]/g, '').toLowerCase()
    let n = s.length, left = 0, right = n - 1;
    while (left < right) {
        if (s[left] !== s[right]) {
            return false
        }
        left++
        right--
    }
    return true
}
  • 时间复杂度: O(∣s∣), 其中 ∣s∣ 是字符串 s 的长度
  • 空间复杂度: 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