码迷,mamicode.com
首页 > 其他好文 > 详细

Valid Palindrome--LeetCode

时间:2015-04-01 13:28:54      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

题目:

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.

思路:从两头开始往中间靠拢,需要进行比对。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
判断一个字符串是否为回文字符串 这里只比较字符,大写字符和小写字符
看成是一样的 
*/ 

bool helper(string& str,int begin,int end)
{
	if(begin == end)
		return true;
	if(begin > end)
		return false;
	if(isalpha(str[begin]) && isalpha(str[end]))
	{
		if(toupper(str[begin]) == toupper(str[end]))
			return helper(str,begin+1,end-1);
		else
			return false;
	}
	else if(!isalpha(str[begin]) && isalpha(str[end]))
		return helper(str,begin+1,end);
	else if(isalpha(str[begin]) && !isalpha(str[end]))
		return helper(str,begin,end-1);
	else
		return helper(str,begin+1,end-1);
}

bool isVaildPalindrome(string& str)
{
	if(str.length()==0)
		return 0;
	return helper(str,0,str.length()-1);
}

int main()
{
	string str("A man, a plan, a canal: Panama");
	cout<<isVaildPalindrome(str);
	return 0;
}


Valid Palindrome--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44804395

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!