程序员人生 网站导航

LeetCode Valid Palindrome

栏目:综合技术时间:2015-08-07 08:29:20

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

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐