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.
这道题有很多种解法,比如先去掉冗余字符,然后判断一个干净的纯小写字符串;或者两个指针一前一后向中间遍历,遇到冗余字符跳过。。
判断一个纯小写字符串是否是回文也有不同的办法,比如前后两个指针往中间扫;或者找到中点往两边扩展;或者
可以利用回文的子结构性质,DP。公式就是
f(i,j)=f(i+1,j-1)&&s[i]==s[j], 0<=i<j<=n-1
f(i,j)=true, i>=j
我们采用最简单的第一种方法,注意字符串长度为奇偶数时都可以用这段code来做:
- for(int j=0;j<t.length()/2;j++){
- if(t[j]!=t[t.length()-1-j])
- return false;
- }
- return true;
代码如下:
- bool isPalindrome(string s) {
- string t;
- for(int i=0;i<s.length();i++){
- if(s[i]>='a' && s[i]<='z'){
- t+=s[i];
- }
- else if(s[i]>='A' && s[i]<='Z'){
- t+=s[i]-'A'+'a';
- }
- else if(s[i]>='0' && s[i]<='9'){
- t+=s[i];
- }
- }
- for(int j=0;j<t.length()/2;j++){
- if(t[j]!=t[t.length()-1-j])
- return false;
- }
- return true;
- }
<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(1) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
评论热议
本文探讨了如何判断一个字符串是否为回文,主要考虑字母数字字符并忽略大小写。介绍了几种方法,如清理字符串后使用双指针验证,以及利用回文的子结构性质通过动态规划解决。
157

被折叠的 条评论
为什么被折叠?



