《leetCode》:Valid Palindrome
4628 ワード
タイトル
構想
この問題は比較的簡単で、前と後の2つのポインタで移動比較すればよいが、2つのポインタが指す文字が等しいかどうかを比較する前に2つの点を考慮しなければならない.2つ目は、すべて小文字に変換することです.
実装コードは次のとおりです.
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.
構想
この問題は比較的簡単で、前と後の2つのポインタで移動比較すればよいが、2つのポインタが指す文字が等しいかどうかを比較する前に2つの点を考慮しなければならない.2つ目は、すべて小文字に変換することです.
実装コードは次のとおりです.
/*
: ,
:
*/
bool isValid(char ch){
if(('a'<=ch&&ch<='z')||('A'<=ch&&ch<='Z')||('0'<=ch&&ch<='9')){//
return true;
}
else{
return false;
}
}
char capitalTolowercase(char ch){
if('A'<=ch&&ch<='Z'){
return ch+32;
}
else {
return ch;
}
}
bool isPalindrome(char* s) {
if(s==NULL){
return true;
}
int len=strlen(s);
int begin=0;
int end=len-1;
while(begin<end){
if(isValid(s[begin])&&isValid(s[end])){
if(capitalTolowercase(s[begin])==capitalTolowercase(s[end])){
begin++;
end--;
}
else{
return false;
}
}
else if(!isValid(s[begin])&&isValid(s[end])){
begin++;
}
else if(isValid(s[begin])&&!isValid(s[end])){
end--;
}
else if(!isValid(s[begin])&&!isValid(s[end])){
begin++;
end--;
}
}
return true;
}