转载

LeetCode Valid Palindrome

1.题目

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.解答

首先是题目的意思是:判断一个句子,正的读和倒着读是否都一样。比如”abba”,就是正读和倒读都一样。这题只是多少忽略大小写,忽略非字母和数字。所以 "A man, a plan, a canal: Panama" 正读和倒读是一样的。

class Solution { public:  bool isValideChar(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;  }  char tolowerCase(char c){   if(c >= 'A' && c <= 'Z'){    return c - 'A' + 'a';   }else{    return c;   }  }  bool isPalindrome(string s) {   int left = 0;   int right = s.size() - 1;   if(s.size() == 0){    return true;   }   int sSize = s.size();   while((isValideChar(s[left]) == false) && left < s.size()){        ++left;     }     while((isValideChar(s[right]) == false) && right >= 0){        --right;     }   while(left < right){    if(tolowerCase(s[left]) == tolowerCase(s[right])){     ++left;     while((isValideChar(s[left]) == false) && left < s.size()){        ++left;     }     --right;     while((isValideChar(s[right]) == false) && right >= 0){        --right;     }    }else{     return false;    }   }   return true;  } }; 

还是比较容易的,一个指向前,一个指向后,进行比较,过滤掉非字母数字。

正文到此结束
Loading...