Hard-题目46:214. Shortest Palindrome
2016-05-31 23:52
387 查看
题目原文:
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”.
题目大意:
给出一个字符串s,在左边添加尽可能少的字符,使得增加后的字符串是回文串。
题目分析:
本题的关键是求以s[0]开头的最长回文子串,再把剩下的部分翻转搬到前面即可。首先考虑暴力解法,提交显然tle。根据前面题的经验,可以使用manacher算法在O(n)内求出一个字符串的最大回文子串。那么加一个限定p[i]==i就可以得出s[0]开头的最长回文字串。(别问我为什么 我也不知道,我连manacher算法怎么回事都不知道)
源码:(language:cpp)
成绩:
12ms,25.88%,8ms,47.74%
Cmershen的碎碎念:
可能是本题的数据还是有点弱,似乎这个O(n)比很多O(n2)的提交还慢。当然Manacher本来就是很复杂的O(n)算法。
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”.
题目大意:
给出一个字符串s,在左边添加尽可能少的字符,使得增加后的字符串是回文串。
题目分析:
本题的关键是求以s[0]开头的最长回文子串,再把剩下的部分翻转搬到前面即可。首先考虑暴力解法,提交显然tle。根据前面题的经验,可以使用manacher算法在O(n)内求出一个字符串的最大回文子串。那么加一个限定p[i]==i就可以得出s[0]开头的最长回文字串。(别问我为什么 我也不知道,我连manacher算法怎么回事都不知道)
源码:(language:cpp)
class Solution { public: int longestPalindrom(string s) { string s1; s1.resize(2 * s.length() + 2); int idx = 0; s1[idx++] = '$'; s1[idx++] = '#'; for (char a : s) { s1[idx++] = a; s1[idx++] = '#'; } vector<int> p(s1.length(), 0); int res = 0; for (int id = 0, i = 1; i < s1.length(); ++i) { if (i < id + p[id]) p[i] = min(p[2 * id - i], id + p[id] - i); else p[i] = 1; while (s1[i + p[i]] == s1[i - p[i]]) ++p[i]; if (id + p[id] < i + p[i]) id = i; if (p[i] == i) res = max(res, i); } return res - 1; } string shortestPalindrome(string s) { int pos = longestPalindrom(s); string res; for (int i = s.length() - 1; i >= pos; --i) res.push_back(s[i]); return res + s; } };
成绩:
12ms,25.88%,8ms,47.74%
Cmershen的碎碎念:
可能是本题的数据还是有点弱,似乎这个O(n)比很多O(n2)的提交还慢。当然Manacher本来就是很复杂的O(n)算法。
相关文章推荐
- 从键盘上读入平面上两个圆的圆心坐标和半径,确定它们之间的关系(相交、相切、不相交)。
- proc 文件的创建流程及其安全分析
- JS函数(内置函数)
- Http格林尼治时间和毫秒的相互转化EEE, dd MMM y HH:mm:ss 'GMT'
- 观察者模式(Observer Pattern)
- C#中Length和Count的区别(个人观点)
- QT GUI(主)线程与子线程之间的通信——使用跨线程的信号槽
- Hard-题目45:140. Word Break II
- DKMS Create RPM Notes-1
- Hard-题目44:30. Substring with Concatenation of All Words
- 【备忘】C#语言基础-1
- chrome49浏览器 以上跨域
- Hard-题目43:174. Dungeon Game
- 初入ACM
- Hard-题目42:321. Create Maximum Number
- 日常css技巧小结(1)--背景透明度改变对内容无影响
- 高效学习Linux驱动开发
- 我的新浪博客
- Hard-题目41:76. Minimum Window Substring
- 一天一个shell命令 文本操作系列-comm命令用法