【回文】leetcode - Shortest Palindrome
2015-06-05 11:01
369 查看
题目:
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given
Given
分析:
利用manacher算法进行求解,时间复杂度O(n),空间复杂度O(n).
Shortest Palindrome
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.For example:
Given
"aacecaaa", return
"aaacecaaa".
Given
"abcd", return
"dcbabcd".
分析:
利用manacher算法进行求解,时间复杂度O(n),空间复杂度O(n).
class Solution { public: string shortestPalindrome(string s) { if(s.size()<=1) return s; string str(s.size()*2+1,'#'); for(int i=0,j=1;i<s.size();++i,j+=2) str[j]=s[i]; int res=1,id=1,size=str.size(); vector<int> p(size,1); p[1]=2; for(int i=2;i<=size/2;++i) { int maxright=p[id]+id-1; if(i>maxright) { //注意检查越界 while(i - p[i]>=0 && str[i+p[i]]==str[i-p[i]]) ++p[i]; } else { int idleft=id-p[id]+1; int k=i-id,j=id-k,tmp=j-p[j]+1;//i和j关于id对称 if(tmp>idleft) p[i]=p[j]; else if(tmp<idleft) p[i]=p[id]-k; else { p[i]=p[j]; while(i - p[i]>=0 && str[i+p[i]]==str[i-p[i]]) ++p[i]; } } if(p[i]+i>p[id]+id) id=i; if(i-p[i]+1==0) res=i; } if (res == s.size()) return s; else { string tmp = string(s.begin() + res, s.end()); reverse(tmp.begin(), tmp.end()); return tmp + s; } } };
相关文章推荐
- linux常用操作命令
- angularjs directive design made easy
- 浏览器页面是否缩放问题。
- jQuery 语法(一)
- 操作系统-进程管理-进程概要
- SOUI开发者论坛
- 博客地址更换http://my.oschina.net/conniewu
- centos 设置防火墙(记录)
- 圆形进度条的实现方法
- sqlserver导出 数据字典的SQL语句
- 戏(细)说Executor框架线程池任务执行全过程(上)
- leetcode_129题——Sum Root to Leaf Numbers(基于DFS的递归)
- DFS模板——HDU2181哈密顿绕行世界问题
- 本地不安装Oracle,plsql远程连接数据库
- 【leetcode】3sums
- JAVA 对象引用,以及对象赋值(很好的解释)
- Nagios简介
- java 汉字排序(java.text.Collator)
- Google Mock启蒙篇 [1] (Google C++ Mocking Framework for Dummies 翻译)
- How to install, compile, and utilize Rebar in Windows