Valid Palindrome (Easy)

Description

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.

Analysis

简单字符串模拟

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//C++
class Solution {
bool isok(char c){
if(c>='A'&&c<='Z')
return true;
if(c>='a'&&c<='z')
return true;
if(c>='0'&&c<='9')
return true;
return false;
}
string trim(string s){
string ans;
for(int i = (int)s.length()-1;i>=0;i--){
if(!isok(s[i]))
continue;
if(s[i]>='A'&&s[i]<='Z')
s[i] = s[i]-'A'+'a';
ans+=s[i];
}
return ans;
}
public:
bool isPalindrome(string s) {
string ans = trim(s);
int len = ans.length();
for(int i=0;i<len/2;i++){
if(ans[i]!=ans[len-i-1])
return false;
}
return true;
}
};