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

leetcode_125题——Valid Palindrome(string,比较常规思路)

时间:2015-04-20 23:54:15      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

Valid Palindrome

 Total Accepted: 48909 Total Submissions: 221328My Submissions

 

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.

 

Hide Tags
 Two Pointers String
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

   这道题,采用先将数字和字母都提取出来,然后再将这些字母一个从前往后,一个从后往前进行比较

#include<iostream>
#include<string>

using namespace std;

bool isPalindrome(string s) {
	if(s.empty())
		return 1;
	int len=s.size();
	int i=0;
	int flag=0;//作为标志是否全部为空
	string temp;
	while(i<len)
	{
		if(s[i]!=‘ ‘)
			flag=1;
		if((s[i]>=48&&s[i]<=57)||(s[i]>=65&&s[i]<=90)||(s[i]>=97&&s[i]<=122))
			temp.push_back(s[i]);
		i++;
	}

	if(flag==0)//若全为空,直接退出
		return 1;

	int len_temp=temp.size();
	i=0;
	while(i<len_temp/2)
	{
		if( (temp[i]==temp[len_temp-i-1])||//比如a=a
			((temp[i]>=65&&temp[i]<=97)&&(temp[i]==temp[len_temp-i-1]-32))||//比如a=A
			(((temp[i]==temp[len_temp-i-1]+32))&&(temp[i]>=97&&temp[i]<=122))//比如A=a
			)
		{i++;}
		else
			return 0;		
	}
	return 1;
}
int main()
{
	string str="ab";
	cout<<isPalindrome(str)<<endl;
	system("pause");
	return 1;
}

  

 

leetcode_125题——Valid Palindrome(string,比较常规思路)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4442845.html

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