[LintCode] Valid Palindrome 验证回文字符串

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Notice

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.

Have you met this question in a real interview?
 
 
Example

"A man, a plan, a canal: Panama" is a palindrome.

"race a car" is not a palindrome.

Challenge

O(n) time without extra memory.

LeetCode上的原题,请参见我之前的博客Valid Palindrome

解法一:

class Solution {
public:
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
bool isPalindrome(string& s) {
int left = , right = s.size() - ;
while (left < right) {
if (!isAlNum(s[left])) ++left;
else if (!isAlNum(s[right])) --right;
else if ((s[left] + - 'a') % != (s[right] + - 'a') % ) return false;
else {
++left; --right;
}
}
return true;
}
bool isAlNum(char c) {
if (c >= 'a' && c <= 'z') return true;
if (c >= 'A' && c <= 'Z') return true;
if (c >= '' && c <= '') return true;
return false;
}
};

解法二:

class Solution {
public:
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
bool isPalindrome(string& s) {
int left = , right = s.size() - ;
while (left < right) {
if (!isalnum(s[left])) ++left;
else if (!isalnum(s[right])) --right;
else if ((s[left] + - 'a') % != (s[right] + - 'a') % ) return false;
else {
++left; --right;
}
}
return true;
}
};
上一篇:【C#小知识】C#中一些易混淆概念总结(五)---------继承 分类: C# 2014-02-06 22:05 1106人阅读 评论(0) 收藏


下一篇:MapHttpRoute