1,题目要求
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:
Input: “race a car”
Output: false
给定一个字符串,确定它是否是回文,只考虑字母数字字符并忽略大小写。
注意:出于此问题的目的,我们将空字符串定义为有效回文。
2,题目思路
对于这道题,要求判断一个字符串是否是一个回文串。
所谓回文串,就是从左往右与从右往左读都是一样的。
这道题的特殊之处在于,给定的字符串并不是一连串的小写字母的形式,因此,我们需要将所有的字母提取出来,并将所有大写字母转化为小写字母即可。
3,代码实现
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
bool isPalindrome(string s) {
string tmp = "";
for(char &c : s)
if(isalnum(c))
tmp += tolower(c);
if(tmp.size()<2) return true;
for(int i = 0, j = tmp.size()-1;i<tmp.size()/2;i++,j--)
if(tmp[i] != tmp[j])
return false;
return true;
}
};