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 #33

Open
sl1673495 opened this issue May 16, 2020 · 1 comment
Open

验证回文串-125 #33

sl1673495 opened this issue May 16, 2020 · 1 comment

Comments

@sl1673495
Copy link
Owner

sl1673495 commented May 16, 2020

125.验证回文串

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。

说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

输入: "A man, a plan, a canal: Panama"
输出: true

示例 2:

输入: "race a car"
输出: false

https://leetcode-cn.com/problems/valid-palindrome

思路

先根据题目给出的条件,通过正则把不匹配字符去掉,然后转小写。

建立双指针 i, j 分别指向头和尾,然后两个指针不断的向中间靠近,每前进一步就对比两端的字符串是否相等,如果不相等则直接返回 false。

如果直到 i >= j 也就是指针对撞了,都没有返回 false,那就说明符合「回文」的定义,返回 true。

/**
 * @param {string} s
 * @return {boolean}
 */
let isPalindrome = function(s) {
    s = s.replace(/[^0-9a-zA-Z]/g, '').toLowerCase()
    let i = 0
    let j = s.length - 1

    while(i < j) {
        let head = s[i]
        let tail = s[j]

        if (head !== tail) {
            return false
        }else {
            i++
            j--
        }
    }
    return true
};
@gitbu
Copy link

gitbu commented Sep 11, 2023

原题说是“我们将空字符串定义为有效的回文串。”,这个感觉答案里没有考虑到

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants