首页 > 学院 > 开发设计 > 正文

leecode 解题总结:125. Valid Palindrome

2019-11-08 18:43:40
字体:
来源:转载
供稿:网友
#include <iostream>#include <stdio.h>#include <vector>#include <algorithm>#include <string>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 ,highA[low]或者A[high]不是数字或字母,则直接过滤,否则统一将字符转换为小写,并比较是否相等low >= high的时候结束易错:如果是空字符串,直接是回文的。容易遗漏输入:A man, a plan, a canal: Panamarace a car输出:truefalse关键: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<int> nums;	 Solution solution;	 vector<int> 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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表