美文网首页
125. Valid Palindrome

125. Valid Palindrome

作者: Icytail | 来源:发表于2017-11-19 23:14 被阅读0次

Description:

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

My code:

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    let arrBefore = s.toUpperCase().match(/[a-zA-Z0-9]+/g);
    if(arrBefore == null) {
        return true;
    }
    let strBefore = arrBefore.join('');
    let strReverse = strBefore.split('').reverse().join('');
    if(strBefore == strReverse) {
        return true;
    } else {
        return false;
    }
};

Note: 字符串使用match()和toUpperCase()分别去除不需要的字符和忽略大小写,然后转换为数组取反,取反前后的字符串对比是否相等,如果相等即满足回文

相关文章

网友评论

      本文标题:125. Valid Palindrome

      本文链接:https://www.haomeiwen.com/subject/uecuvxtx.html