leetcode第五题—最长回文字符串
2015-07-23 17:52
302 查看
最长回文字符串(Longest Palindromic Substring )
回文字符串都是对称的,有两种对称方式,一是关于字符对称,比如a,aba,cabac,这种回文字符串长度都是奇数;二是关于间隔对称,比如aa,abba,cbaabc,这种回文字符串长度都是偶数,所以要分别检测这两种情况。
中心结点法,就是遍历整个字符串,分别设为中心结点,然后第二个遍历是分别对设定的中心向左右扩展,所以复杂度为o(n^2)。
比如对于字符串abba,先检测关于字符对称,设定中心为a,发现最长回文为a,再检测关于间隔对称,给定中心为ab之间间隔,发现最长回文为空。然后坐标前移,设定中心为b,发现最长回文为b,再设定中心为bb的间隔,发现最长回文为abba,为目前最长,所以最长回文设为abba,然后坐标前移,继续检测。
给定字符串和中心结点及字符串长度,返回以该结点为中心的最长回文字符串
string expandAroundCenter(string &s,int pos1,int pos2,int n) { int lt=pos1; int rt=pos2; while(lt>=0&&rt<=n-1&&s[lt]==s[rt]) { lt--; rt++; } return s.substr(lt+1,rt-lt-1); }
给定字符串,返回最长回文字符串,通过遍历设定中心结点,调用上面的函数实现
string longestPalindrome(string &s) { int n=s.size(); if(n==0) return " "; string longest=s.substr(0,1); for(int i=0;i<n-1;i++) { //center is the character,the length is must be odd //like aba cabac string p1=expandAroundCenter(s,i,i,n); if(p1.size()>longest.size()) longest=p1; //center is the interval,the length is must be even //like bb abba cabbac string p2=expandAroundCenter(s,i,i+1,n); if(p2.size()>longest.size()) longest=p2; } return longest; }
相关文章推荐
- HDU 2046 骨牌铺方格
- 排序算法总结&&java代码实现
- sar命令
- BI Extender
- 浮点数转换成人民币读法字符串
- java处理json
- No result defined for action and result success
- HTTP长连接与短连接
- Web service standards: SOAP, REST, OData, and more
- 使用SpannableString实现一个load小动画
- C++ Primer 复习杂记(第五章)
- 第四章 设计程序架构 之 状态管理
- 实现一个脚本引擎
- 缓存管理
- 设置UIlabel的行高
- mysql进阶(二)索引简易教程
- MyBatis之高级关联和集合映射(一、基础知识)
- MATLAB与R函数对照(3)——输入/创建/索引矩阵函数
- mysql进阶(二)索引简易教程
- 使用批处理文件在FTP服务器 上传下载文件