LeetCode OJ - Valid Palindrome

来源:互联网 发布:ubuntu安装图形化界面 编辑:程序博客网 时间:2024/06/05 21:52

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.

分析:题目比较简单,有效字符为数字和字母,其他无效。注意空字符串、不同测试用例,最好自己写出一些测试用例。

class Solution {public:bool isChar(char ch) {if( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') )return true;return false;}bool isEqual(char A, char B) {                //数字处理if(A >= '0' && B <= '9') {if(A == B)return true;else return false;}                //字母处理char diff = 'A' - 'a';if(A == B  || A + diff == B || A == B + diff)return true;else return false;}bool isPalindrome(string s) {int len = s.size();if(len == 0) return true;int i = 0;int j = len;while(i < j) {//i和j指向有效字符,并且i <= jwhile(!isChar(s[i])) {if(i == j) break;i++;}while(!isChar(s[j])) {if(j == i) break;j--;}//i和j固定位置后比较if(i == j) {return true;}if( i < j && !isEqual(s[i], s[j]) ) {return false;}//下一次比较i++;j--;}if(isEqual(s[i], s[j])) {return true;}return false;}};

出错地方:

       A + 32 == B这里用了char型和int型相加,会将A提升为int型然后相加,故’A‘ + 32 != 'a',低级错误!

       同时有符号的int A和无符号的short B运算,B会被先转化为int,然后在被转化为有符号!

0 0
原创粉丝点击