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

验证回文串 #14

Open
Bulandent opened this issue Jan 25, 2021 · 0 comments
Open

验证回文串 #14

Bulandent opened this issue Jan 25, 2021 · 0 comments

Comments

@Bulandent
Copy link
Owner

Bulandent commented Jan 25, 2021

验证回文串

难度:简单
来源:125. 验证回文串

给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
回文串就是从左往右和从右往左的每个字符都是一样的。
说明:本题中,我们将空字符串定义为有效的回文串。

示例 1:

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

示例 2:

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

思路:

  • 首先需要判空,因为空字符串也是回文,所以如果为空直接返回 true;
  • 然后是需要将字符串不区分大小写,所以需要全部转成小写或者大小;
  • 把得到的字符串转成数组,然后过滤出字母和数字;
  • 最后遍历新数组,使用双指针获取头尾字符判断是否相等,不相等直接返回 false,否则遍历结束则表明它是回文串;
  • 需要注意的是:遍历的时候结束条件是 left < right,这样会比 left <= right 减少一次比较。

题解:

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    if (!s) return true
    let arr = [...s.toLowerCase()].filter(
        item => 'a' <= item && item <= 'z' 
        || '0' <= item && item <= '9')

    let left = 0, right = arr.length - 1
    while(left <= right) {
        if ( arr[left] !== arr[right]) {
            return false
        }
        left++
        right--
    }   
    return true 
};
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

1 participant