leetcode-javascript icon indicating copy to clipboard operation
leetcode-javascript copied to clipboard

验证回文串-125

Open sl1673495 opened this issue 4 years ago • 1 comments

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
};

sl1673495 avatar May 16 '20 16:05 sl1673495

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

gitbu avatar Sep 11 '23 14:09 gitbu