您的位置:首页 > 编程语言 > C语言/C++

Leetcode NO.125 Valid Palindrome

2015-10-11 05:39 399 查看
本题题目要求如下:

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.
本题思路还算简单,就是从两边向中间遍历,如果不是数字和字母,就跳过,如果是,就比较。。。
代码如下:

class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (!isalnum(s[left])) {
++left;
}
else if (!isalnum(s[right])) {
--right;
}
else {
if (tolower(s[left]) != tolower(s[right])) {
cout << left << " " << right << endl;
return false;
}
else {
++left;
--right;
}
}
}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息