思路1——清洗+逆转
代码1
class Solution {
public:
bool isPalindrome(string s) {
string ans;
//字符串清洗
for (char ch: s)
if (isalnum(ch))
ans += tolower(ch);
//字符串逆转
string rev_ans(ans.rbegin(), ans.rend());
return rev_ans==ans;
}
};
思路2——清洗+双向双指针
代码2
class Solution {
public:
bool isPalindrome(string s) {
//字符串清洗 isalnum()判断是否为 数字或字母
string sgood;
for (char ch: s)
if (isalnum(ch))
sgood += tolower(ch);
//双指针遍历
for(int i=0;i<sgood.length()/2;i++)
if(sgood[i]!=sgood[sgood.length()-i-1])
return false;
return true;
}
};
收获
字母判断与转换
isalnum() 判断一个字符是否为字母或数字
islower() 判断一个字符是否为小写字母
issuper() 判断一个字符是否为大写字母
tolower() 将字符转换为小写
tosupper() 将字符转换为大写
字符串逆转
string new_s(s.rbegin(),rend())
reserve(s.begin(),s.end())