题目:
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
functionisPalindrome(s: string): boolean {if (!s) returntrue;constfilterFn=function (str: string): string {constarray=str.split("");returnarray.filter((item) => {constpattern= /\d|[a-z]/;returnpattern.test(item);}).join("");};s=filterFn(s.toLowerCase());consts2=filterFn(s.split("").reverse().join("").toLowerCase());if (s===s2) returntrue;returnfalse;}
functionisPalindrome2(s: string): boolean {
s=s.toLowerCase();
constpattern= /\d|[a-z]/;
constfn=function (index: number, type: string): number {
if (!pattern.test(s[index])) {
type==="left"?index++:index--;
returnfn(index, type);
}
returnindex;
};
letleft=fn(0, "left");
letright=fn(s.length-1, "right");
while (left<right) {
if (s[left] !==s[right]) returnfalse;
left=fn(left++, "left");
right=fn(right--, "right");
}
return true;
}
