双指针,两头向中间走
isalnum用来检测ch是否是字母A到Z或者数字0到9,是字母或数字返回1(或非0),否则返回0;
tolower转小写;
class Solution {
public:
bool isPalindrome(string s) {
if(s.size() < 0)
return true;
int left = 0;
int right = s.size() - 1;
while(left < right){
while(left < right && !isalnum(s[left]))
{
left++;
}
while(left < right && !isalnum(s[right]))
{
right--;
}
if(tolower(s[left]) != tolower(s[right])){
return false;
}
left++;
right--;
}
return true;
}
};
把链表的val存入vector,再用双指针;
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> it;
ListNode* node = head;
while(node){
it.push_back(node->val);
node = node->next;
}
int left = 0;
int right = it.size() - 1;
while(left < right)
{
if(it[left] != it[right]){
return false;
}
right--;
left++;
}
return true;
}
};