leetcode之Valid Palindrome

本文介绍如何使用C++实现判断一个字符串是否为回文串的方法,只考虑字母和数字字符。

题目大意:

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.

意思就是:

给定一个字符串,判断该字符串是否是回文。仅考虑字母和数字,不许考虑空格,逗号等字符。

思路:

一重循环即可解决。设置两个位置变量i和j,i从字符串开头开始往后走,j从字符串结尾开始往前走。遇到非字母和非数字,则不考虑,继续走;遇到字母或数字则进行判断,直到判断完整个字符串。

代码如下:

class Solution{
	public:
		bool isPalindrome(string s){
			int i = 0, j = s.length()-1;
			while(i<j){
				if(!isvalid(s[i])){
					i++;
					continue;
				}
				if(!isvalid(s[j])){
					j--;
					continue;
				}
				if(isdigit(s[i])){
					if(s[i] == s[j]){
						i++;
						j--;
					}
					else{
						return false;
					}
				}
				else if(isalpha(s[i])){
					if(tolower(s[i]) == tolower(s[j])){
						i++;
						j--;
					}
					else{
						return false;
					}
				}
			}
			return true;
		}
		bool isvalid(char s){
			if(isalnum(s)){
				return true;
			}
			else{
				return false;
			}
		}
};

注:string中处理字符的一些有用函数。头文件为:cctype

      isalnum(c)   如果c是字母或数字,则为true。

      isalpha(c)    如果c是字母,则为true。

      isdigit(c)       如果c是数字,则为true。

      tolower(c)    如果c是大写字母,则返回其小写字母,否则直接返回c。

      toupper(c)   如果c是小写字母,则返回其大写字母,否则直接返回c。

      isupper(c)   如果c是大写字母,则返回true。

      islower(c)    如果c是小写字母,则返回true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值