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

判断是否回文字符串 #98

Open
AwesomeDevin opened this issue Sep 14, 2023 · 0 comments
Open

判断是否回文字符串 #98

AwesomeDevin opened this issue Sep 14, 2023 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

AwesomeDevin commented Sep 14, 2023

如果在将所有大写字符转换为小写字符、并移除所有非字母数字字符之后,短语正着读和反着读都一样。则可以认为该短语是一个 回文串 。

字母和数字都属于字母数字字符。

给你一个字符串 s,如果它是 回文串 ,返回 true ;否则,返回 false 。

示例 1:

输入: s = "A man, a plan, a canal: Panama"
输出:true
解释:"amanaplanacanalpanama" 是回文串。
示例 2:

输入:s = "race a car"
输出:false
解释:"raceacar" 不是回文串。
示例 3:

输入:s = " "
输出:true
解释:在移除非字母数字字符之后,s 是一个空字符串 "" 。
由于空字符串正着反着读都一样,所以是回文串。

var isPalindrome = function(s) {
    if(typeof s !== 'string'){
        return false
    }
    s = s.toLocaleLowerCase().replace(/[^a-z0-9]/g,'').toLocaleLowerCase().split('') // 转为小写并去除空字符串
    let startIndex = 0
    let endIndex = s.length - 1
    const middleIndex= Math.floor(s.length / 2)
    for(let i=0; i <= middleIndex ; i++){
        if(s[startIndex + i] !== s[endIndex - i]) return false // 双指针扫描相同字符,扫到即为false
    }
    return true
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant