LeetCode #214 Shortest Palindrome
2015-08-07 19:57
246 查看
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
下面的代码是从Discuss中看到的,借用BM算法的思想,效率很高。
For example:
Given
"aacecaaa", return
"aaacecaaa".
Given
"abcd", return
"dcbabcd".
下面的代码是从Discuss中看到的,借用BM算法的思想,效率很高。
class Solution { public: string shortestPalindrome(string s) { int n = s.length(); if (n < 2) return s; string rs = s; reverse(rs.begin(), rs.end()); int right[26]; for (int i = 0; i < n; i++) right[s[i] - 'a'] = i; int i = 0, j, tmp; while (i < n) { for (j = n - 1 - i; j >= 0; j--) { if (s[j] != rs[i + j]) { tmp = j - right[rs[i + j] - 'a']; if (tmp <= 0) { tmp = i + j + 1; while (tmp < n && rs[tmp] != s[j]) tmp++; tmp = tmp - i - j; } i += tmp; break; } } if (j < 0) return rs.substr(0, i) + s; } return rs.substr(0, n - 1) + s; } };
相关文章推荐
- POJ 2013 Symmetric Order 水
- POJ-1922 Ride to School
- Android Java设置一个图片的颜色为透明色(不显示,不是背景色),可用于无透明通道的ImageView
- ZOJ3818 Pretty Poem(暴力)
- swirl 7: Matrices and Data Frames
- VC程序版本更新后部分客户无法启动
- ACdream 完美数
- 【Cocos2d入门教程一】Cocos2d-x环境搭建
- Course Schedule
- POJ-1316 Self Numbers-自数
- 如何使自己编译的驱动程序具有读写权限
- MFC+OpenGL单文档制作三维图像
- UVA 10020 - Minimal coverage 解题心得
- npm常用命令->nodejs
- 黑马程序员--- objective-c 匿名类的使用
- HDU - 1247 Hat’s Words 字典树
- Java — 开发环境(Core Java I)
- HDU 2700 Parity
- POJ 2864 Pascal Library 水
- 获取android手机版本