回文判定 Valid Palindrome

142 篇文章 20 订阅
45 篇文章 0 订阅

看似简单的问题总是非常容易出错!典型的测试用例非常关键!

问题: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:For the purpose of this problem, we define empty string as valid palindrome.

思路:主题思路非常简单,双指针就行了。但是细节上非常多。

要忽视空格和标点,要忽略大小写。

典型的测试用例:“  ”,  ".,", "a.", ".a", "a0", "aA"

代码:

class Solution {
	public:
		bool isAlphanumeric(const char &a)
		{
			if((a >= 'a' && a <= 'z')||(a >= 'A' && a <= 'Z')||(a >= '0' && a <= '9'))
				return true;
			else
				return false;
		}
		
		bool isEqual(const char &a, const char &b)
		{
		    int x, y;
		    if(a>= 'a' && a <= 'z')
		        x = a - 'a';
		    else if(a>='A'&&a<='Z')
		        x = a - 'A';
		    else
		        x = a - '0' + 100; //将数字的范围和字母区别开!

		    if(b>= 'a' && b <= 'z')
		        y = b - 'a';
		    else if(b>='A'&&b<='Z')
		        y = b - 'A';
		    else
		        y = b - '0' + 100;
		    
		    return (x == y);
		}
		
		bool isPalindrome(string s) {
		    int n = s.size();
			if(n<2)
				return true;
			int left = 0;
			int right = n- 1;
			while(left < right)
			{
				while(left < right && !isAlphanumeric(s[left]))//时刻判断指针是否相遇!
					left++;
				while(left < right && !isAlphanumeric(s[right]))
					right--;
				    
				if((!isAlphanumeric(s[left]))||(isEqual(s[left++],s[right--]))) //考虑全是非字符数字的情况
					continue;
				else
					return false;
			}
			return true;
		}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值