LeetCode : Valid Palindrome
题目原意:判断字符数组(数组中的非数字字符被忽略)是否为回文,及两端往中间结构是否一样。如“ab c .,b a” 为真,”abdeba”为假。
题目原意:判断字符数组(数组中的非数字字符被忽略)是否为回文,及两端往中间结构是否一样。如“ab c .,b a” 为真,”abdeba”为假。
代码如下(leetCode 测得运行时间为4ms):
int isPalindrome(char* s)
{
char *front, *back;
int flag = 0;
int sLen = strlen(s);
if (sLen <= 0 ) //!< 空字符串,也可以判断为 *s == "\0"
{
return 1;
}
front = &s[0];
back = &s[sLen - 1];
while (front <= back) //!< 两端往中间判断,取等号是满足类似" "
{
while(!isdigit(*front) && !isalpha(*front) && (front < back)) //!< 忽略非数字字母元素
++front;
while(!isdigit(*back) && !isalpha(*back) && (front < back))
--back;
if ((*front != *back) && ((*front - 32) != *back) && (*front != (*back - 32)) )
{ //!< 不满足规则,返回0
return 0;
}
else
{ //!< 两端向中间偏移
++front;
--back;
flag = 1;
}
}
return flag;
}