首页 > 代码库 > Valid Palindrome
Valid Palindrome
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.
其实就是忽略各种符号的且忽略大小写的,另类版本的回文字符串的判断。
代码:
class Solution {public: bool ignorecase(char a,char b) { if(ok2(a)&&ok2(b)) //若是字母,忽略大小写 return a==b||a==(b+32)||a==(b-32)||(a+32)==b||(a-32)==b; else//否则是数字,直接比较 return a==b; } bool ok(char a) { return (a>=‘0‘&&a<=‘9‘)||(a>=‘a‘&&a<=‘z‘)||(a>=‘A‘&&a<=‘Z‘); } bool ok2(char a) { return (a>=‘a‘&&a<=‘z‘)||(a>=‘A‘&&a<=‘Z‘); } bool isPalindrome(string s) { if(s.empty()||s.size()==1) return true; int len=s.size(); int i,j,q; for(q=0;q<s.size();++q) { if(ok(s[q])) break; } if(q==s.size())//全部是非字母 return true; for(i=0,j=len-1;i<j;++i,--j)//两指针从头和尾向中间缩进,遇到非字母跳过 { if(ok(s[i])&&ok(s[j])) { if(!ignorecase(s[i],s[j])) return false; } else if(ok(s[i])&&!ok(s[j])){--i;}//j位置为符号,所以i维持在原来位置 else if(!ok(s[i])&&ok(s[j])){++j;} } if(i==j||i==(j+1)) return true; else return false; }};
Valid Palindrome
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。