Skip to content

Instantly share code, notes, and snippets.

@monsterooo
Last active February 13, 2019 13:53
Show Gist options
  • Save monsterooo/f5a90092ed28bd0a1061794c807e6f39 to your computer and use it in GitHub Desktop.
Save monsterooo/f5a90092ed28bd0a1061794c807e6f39 to your computer and use it in GitHub Desktop.
算法练习-回文字符串判断
/**
* 回文字符串判断
*/
function isPalindrome(s) {
if (!s) return true;
var i = 0, j = s.length - 1;
for (; i < j; ++i, --j ) {
while (i < j && !isAlphaNumber(s[i])) ++i;
while(i < j && !isAlphaNumber(s[j])) --j;
if (i < j && !isEqualIgnoreCase(s[i], s[j])) return false;
}
return true;
}
var s = 'race a E-car';
var palindrome = isPalindrome(s);
console.log(s + (palindrome ? '是一个' : '不是一个') + '回文字符串');
/**
* 判断一个字符是否是字母或数字(a-zA-Z0-9)
*/
function isAlphaNumber(c) {
return (c >= 'a' && c<= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
/**
* 判断两个字符是否相等(忽略大小写)
*/
function isEqualIgnoreCase(s1, s2) {
if (s1 >= 'A' && s1 <= 'Z') s1 = s1.toLowerCase()
if (s2 >= 'A' && s2 <= 'Z') s2 = s2.toLowerCase();
return s1 === s2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment