题目
Valid Palindrome
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.
分析
就是去掉非数字和字母的字符,忽略大小写,然后两头开始比较。思路很简单。
我对string的函数不熟悉,所以采用的是c风格的方式,方法比较low,速度还可以。
class Solution {
public:
bool isPalindrome(string s) {
int i = 0;
int j = s.size()-1;
while (i<j)
{
if (!(s[i]>='a'&&s[i]<='z') && !(s[i]>='A'&&s[i]<='Z') &&!(s[i]>='0'&&s[i]<='9'))
{
i++;
continue;
}
if (!(s[j]>='a'&&s[j]<='z') && !(s[j]>='A'&&s[j]<='Z')&&!(s[j]>='0'&&s[j]<='9'))
{
j--;
continue;
}
if (s[i] != s[j] && abs(s[i] - s[j])!='a'-'A')
{
char s1 = s[i];
char s2 = s[j];
return false;
}
else
{
i++;
j--;
}
}
return true;
}
};
下面看看大神写的,真正利用了string函数的代码
class Solution {
public:
bool isPalindrome(string s) {
transform(s.begin(), s.end(), s.begin(), ::tolower);
auto left = s.begin(), right = prev(s.end());
while (left < right) {
if (!::isalnum(*left)) ++left;
else if (!::isalnum(*right)) --right;
else if (*left != *right) return false;
else{ left++, right--; }
}
return true;
}
};
需要注意的知识点
1.transform函数
该算法用于实行容器元素的变换操作。有如下两个使用原型,一个将迭代器区间[first,last)中元素,执行一元函数对象op操作,交换后的结果放在[result,result+(last-first))区间中。另一个将迭代器区间[first1,last1)的元素*i,依次与[first2,first2+(last-first))的元素*j,执行二元函数操作binary_op(*i,*j),交换结果放在[result,result+(last1-first1))。
参考自 http://blog.csdn.net/jerryjbiao/article/details/7523110
例如将first中的元素全部变成小写然后保存在second中
int main()
{
string first,second;
cin>>first;
second.resize(first.size());
transform(first.begin(),first.end(),second.begin(),op);
cout<<second<<endl;
return 0;
}
其中
char op(char ch)
{
if(ch>='A'&&ch<='Z')
return ch+32;
else
return ch;
}
而代码中的::tolower函数直接实现了字符小写的功能。
2.prev 函数
right = prev(s.end());指的应该是s的前一位。s.end()已经到结尾,指向空了。
3.::isalnum函数
extern int isalnum(int c);:
功能:判断字符变量c是否为字母或数字
说明:当c为数字0-9或字母a-z及A-Z时,返回非零值,否则返回零。
extern int isupper(int c);
说明:当参数c为大写英文字母(A-Z)时,返回非零值,否则返回零。
附加说明: 此为宏定义,非真正函数。
int islower(int c)
检查参数c是否为小写英文字母。
返回值
若参数c为小写英文字母,则返回TRUE,否则返回NULL(0)。
附加说明
此为宏定义,非真正函数。