leecode 解题总结:125. Valid Palindrome

#include 
#include 
#include 
#include 
#include 
using namespace std;
/*
问题:
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.

分析:此题实际是判断一个字符串是否是回文字符串,不考虑大小写,比较的时候只比较字母和数字,对于其他字符默认忽略。
设定从前向后和从后向前两个指针分别为low ,high
A[low]或者A[high]不是数字或字母,则直接过滤,
否则统一将字符转换为小写,并比较是否相等
low >= high的时候结束

易错:如果是空字符串,直接是回文的。容易遗漏

输入:
A man, a plan, a canal: Panama
race a car
输出:
true
false

关键:
1 易错:如果是空字符串,直接是回文的。容易遗漏
2 将字符串转换为小写,用的是transform函数(beg , end , where  , func)
transform(s.begin() , s.end() , s.begin() , tolower);
*/

class Solution {
public:
    bool isPalindrome(string s) {
		if(s.empty())      
		{
			return true;
		}
		//将字符串转换为小写,用的是transform函数(beg , end , where  , func)
		//transform(s.begin() , s.end() , s.begin() , tolower);
		int len = s.length();
		for(int i = 0 ; i < len ; i++)
		{
			if('A' <= s.at(i) && s.at(i) <= 'Z')
			{
				s.at(i) = s.at(i) - 'A' + 'a';
			}
		}
		int low = 0;
		int high = len - 1;
		while(low < high)
		{
			while(low < high && !(
				 ('0' <= s.at(low) && s.at(low) <= '9') || 
				 ('a' <= s.at(low) && s.at(low) <= 'z') ) )
			{
				low++;
			}
			if(low >= high)
			{
				return true;
			}
			while(low < high && !(
				 ('0' <= s.at(high) && s.at(high) <= '9') || 
				 ('a' <= s.at(high) && s.at(high) <= 'z') ) )
			{
				high--;
			}
			if(low >= high)
			{
				return true;
			}
			//比较两个字符是否相同,先转换为小写,比较之后,还需要变换下标
			if(s.at(low) != s.at(high))
			{
				return false;
			}
			low++;
			high--;
		}
		return true;
    }
};

void process()
{
	 vector nums;
	 Solution solution;
	 vector result;
	 char str[1024];
	 //对于有空格的字符串,直接用gets
	 while(gets(str) )
	 {
		 string value(str);
		 bool isOk = solution.isPalindrome(value);
		 if(isOk)
		 {
			cout << "true" << endl;
		 }
		 else
		 {
			 cout << "false" << endl;
		 }
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}


你可能感兴趣的:(leecode)