题目:
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.
译文:
给定一个字符串,确定它是否是回文,只考虑字母数字字符和忽略大小写。
例如:
Input | Output |
---|---|
“A man, a plan, a canal: Panama” | true |
“race a car” | false |
思路:
1.利用对撞指针进行遍历字符串进行判断。
2.使用库函数简化过程
代码实现:
bool isPalindrome(string s)
{
for (int i = 0, j = s.size() - 1; i < j; i++, j--)//i==j此处不用判断
{
while (isalnum(s[i]) == false && i < j)i++;
while (isalnum(s[j]) == false && i < j)j--;
if (toupper(s[i]) != toupper(s[j]))
{
return false;
}
}
return true;
}
附录
库函数的使用:
1.int isalnum ( int c );//判断字符是否是数字或者是字母
Check if character is alphanumeric
Checks if parameter c is either a decimal digit or an uppercase or lowercase letter.The result is true if either isalpha or isdigit would also return true.
2.int toupper ( int c );//字符小写转化为大写
Convert lowercase letter to uppercase