您的位置:首页 > 其它

【LeetCode】之Valid Palindrome

2015-09-05 21:25 459 查看
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.

此题的目的在于判断一个字符串是否是回文字符串,即正着读反着读都是一样的,题目中只考虑字母和数字,且不考虑大小写。

思路:

1.因为不考虑字母的大小写,所以将字符串统一转换为小写;

2.然后定义两个指针,指向字符串的头和尾;

3.然后开始判断头和尾的字符,分两种情况:

(1)头和尾的字符不相同,直接返回false;

(2)头和尾相同或者头和尾不是字母和数字,则头的指针往后走,尾的指针往前走,知道他们会合,跳出循环,返回true。

class Solution {
public:
bool isPalindrome(string s) {
transform(s.begin(),s.end(),s.begin(),::tolower);//将大写字母转换为小写
auto left = s.begin();
auto 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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode string