标签:style blog class c code java
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.
思路1:首先定义一个函数判断一个字符是不是符合规则——字符和数字(不包含空格、标点符号等),然后在按照判断回文结构的经典规则,定义前后两个指针,如果前后两个指针的内容不符合规则,则begin++,end--,再者判断是否为回文结构。
class Solution { public: bool isChar(char &ch) { if(ch>=‘0‘ && ch<=‘9‘) return true; else if(ch>=‘a‘ && ch<=‘z‘) return true; else if(ch>=‘A‘&&ch<=‘Z‘) { ch+=32; return true; } return false; } bool isPalindrome(string s) { if(s=="") return true; int n=s.size(); int begin=0; int end=n-1; while(begin<end) { if(!isChar(s[begin])) begin++; else if(!isChar(s[end])) end--; else if(s[begin++]!=s[end--]) { return false; } } return true; } };
思路2:设置一个字符串变量str,将原字符串中数字和字符不包含标点空格等纳入str,如果出现大写字母,则将其转变为小写字母。这样就得到了只包含字符和数字的字符串了,然后判断其是否为回文串。
class Solution { public: bool isPalindrome(string s) { if(s=="") return true; string str=""; int n=s.size(); for(int i=0;i<n;i++) { if((s[i]>=‘a‘&&s[i]<=‘z‘)||(s[i]>=‘0‘&&s[i]<=‘9‘)||(s[i]>=‘A‘&&s[i]<=‘Z‘)) { if(s[i]>=‘A‘&&s[i]<=‘Z‘) str+=(s[i]-‘A‘+‘a‘); else str+=s[i]; } } for(int i=0;i<str.size();i++) { if(str[i]!=str[str.size()-i-1]) return false; } return true; } };
Valid Palindrome,布布扣,bubuko.com
标签:style blog class c code java
原文地址:http://www.cnblogs.com/awy-blog/p/3739404.html