LeetCode Valid Palindrome
來源:程序員人生 發布時間:2015-08-07 08:29:20 閱讀次數:2531次
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.解答
首先是題目的意思是:判斷1個句子,正的讀和倒著讀是不是都1樣。比如"abba",就是正讀和倒讀都1樣。這題只是多少疏忽大小寫,疏忽非字母和數字。所以"A man, a plan, a canal: Panama"
正讀和倒讀是1樣的。
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;
}
};
還是比較容易的,1個指向前,1個指向后,進行比較,過濾掉非字母數字。
http://www.waitingfy.com/archives/1680
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈