125. Valid Palindrome
2017-11-19 本文已影响0人
Icytail
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()分别去除不需要的字符和忽略大小写,然后转换为数组取反,取反前后的字符串对比是否相等,如果相等即满足回文