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) |
给主人留下些什么吧!~~
评论热议
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值