Leetcode---Valid Palindrome

来源:互联网 发布:阿里云主机80端口打开 编辑:程序博客网 时间:2024/06/08 06:46

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

上一篇:Leetcode---Unique Binary Search Trees II

下一篇:Leetcode---Palindrome Number

相关热门文章
  • test123
  • 编写安全代码——小心有符号数...
  • 使用openssl api进行加密解密...
  • 一段自己打印自己的c程序...
  • sql relay的c++接口
  • 谁能够帮我解决LINUX 2.6 10...
  • 现在的博客积分不会更新了吗?...
  • shell怎么读取网页内容...
  • ssh等待连接的超时问题...
  • curl: (56) Recv failure: Con...
给主人留下些什么吧!~~
原创粉丝点击