LeetCode:Longest Palindromic Substring 最长回文子串
2016-08-18 10:06
435 查看
最长回文子序列,博文链接:http://www.cnblogs.com/TenosDoIt/p/3675788.html
//核心代码 class Solution { public: string longestPalindrome(string s) { const int len = s.size(); if(len <= 1)return s; //Manncher算法 ,o(n) string str = preProcess(s); int n = str.size(), id = 0, mx = 0; vector<int>p(n, 0); for(int i = 1; i < n-1; i++) { p[i] = mx > i ? min(p[2*id-i], mx-i) : 1; //if(mx <= i || (mx > i && p[2*id-i] == mx - i)) //根据正文斜体部分的注释,这里可要可不要 while(str[i+p[i]] == str[i-p[i]])p[i]++; if(i + p[i] > mx) { mx = i + p[i]; id = i; } } //遍历p,寻找最大回文长度 int maxLen = 0, index = 0; for(int i = 1; i < n-1; i++) if(p[i] > maxLen) { maxLen = p[i]; index = i; } return s.substr((index - maxLen)/2, maxLen-1); } //预处理字符串,abc预处理后变成$#a#b#c#^ string preProcess(const string &s) { int n = s.size(); string res; res.push_back('$');//把$放到字符串头部 res.push_back('#');//以#作为原来字符串中每个字符的间隔 for(int i = 0; i < n; i++) { res.push_back(s[i]); res.push_back('#'); } res.push_back('^');//以^作为字符串的结尾 return res; } };
相关文章推荐
- Scala的核心力量和黄金定律
- 自定义ActionBar,在BaseActivity如何降低耦合
- 发现一个免费邮件代发平台,sendpost.cn
- Android混淆——混淆代码总结
- aaaaaaaaaaaaaaa
- JS 学习(四)对象
- iOS - OC Category 分类
- atoi函数的实现
- 麻省理工告诉我们男女配对的真相
- 数组排序sort()
- OpenSceneGraph实现的NeHe OpenGL教程 - 第三十八课
- 分治法写划分数
- 使用聚合函数group by后面必须要带着所有要查询的列,但是我只想根据group by后面的第一个列进行分组,怎么办? [
- springMvc IE浏览器 前台中文参数 乱码问题解决方法
- 你知道C#中的Lambda表达式的演化过程吗
- C语言头文件的包含顺序
- 苹果剪切板,涨姿势了UIPasteboard
- View绘制流程资料
- CoordinatorLayout高级用法-自定义Behavior
- OpenSceneGraph实现的NeHe OpenGL教程 - 第三十九课