Valid Palindrome
Total Accepted: 48909 Total Submissions: 221328My Submissions
Question Solution
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.
Hide Tags
Have you met this question in a real interview?
Yes
No
这道题,采用先将数字和字母都提取出来,然后再将这些字母一个从前往后,一个从后往前进行比较
#include<iostream> #include<string> using namespace std; bool isPalindrome(string s) { if(s.empty()) return 1; int len=s.size(); int i=0; int flag=0;//作为标志是否全部为空 string temp; while(i<len) { if(s[i]!=‘ ‘) flag=1; if((s[i]>=48&&s[i]<=57)||(s[i]>=65&&s[i]<=90)||(s[i]>=97&&s[i]<=122)) temp.push_back(s[i]); i++; } if(flag==0)//若全为空,直接退出 return 1; int len_temp=temp.size(); i=0; while(i<len_temp/2) { if( (temp[i]==temp[len_temp-i-1])||//比如a=a ((temp[i]>=65&&temp[i]<=97)&&(temp[i]==temp[len_temp-i-1]-32))||//比如a=A (((temp[i]==temp[len_temp-i-1]+32))&&(temp[i]>=97&&temp[i]<=122))//比如A=a ) {i++;} else return 0; } return 1; } int main() { string str="ab"; cout<<isPalindrome(str)<<endl; system("pause"); return 1; }
时间: 2024-10-11 01:41:06