Leetcode---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.

这道题有很多种解法,比如先去掉冗余字符,然后判断一个干净的纯小写字符串;或者两个指针一前一后向中间遍历,遇到冗余字符跳过。。

判断一个纯小写字符串是否是回文也有不同的办法,比如前后两个指针往中间扫;或者找到中点往两边扩展;或者
可以利用回文的子结构性质,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来做:


  1. for(int j=0;j<t.length()/2;j++){
  2.             if(t[j]!=t[t.length()-1-j])
  3.                 return false;
  4.         }
  5.         return true;


代码如下:

  1. bool isPalindrome(string s) {
  2.         string t;
  3.         for(int i=0;i<s.length();i++){
  4.             if(s[i]>='a' && s[i]<='z'){
  5.                 t+=s[i];
  6.             }
  7.             else if(s[i]>='A' && s[i]<='Z'){
  8.                 t+=s[i]-'A'+'a';
  9.             }
  10.             else if(s[i]>='0' && s[i]<='9'){
  11.                 t+=s[i];
  12.             }
  13.         }
  14.         for(int j=0;j<t.length()/2;j++){
  15.             if(t[j]!=t[t.length()-1-j])
  16.                 return false;
  17.         }
  18.         return true;
  19.     }


<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) |
给主人留下些什么吧!~~
评论热议
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值