Leetcode242: Shortest Palindrome
来源:互联网 发布:音乐播放器js代码 编辑:程序博客网 时间:2024/05/16 04:26
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"
.
class Solution {public: bool isPalindrome(string s, int start, int end) { while(start<end) { if(s[start] != s[end]) return false; start++; end--; } return true; } string shortestPalindrome(string s) { int pos = s.length()-1; if(pos==0) return s; for(; pos>0; pos--) if(s[pos]==s[0] && isPalindrome(s, 0, pos)) break; string res; for(int i = s.length()-1; i > pos; i--) res.push_back(s[i]); res+=s; return res; }};
这种方法时间复杂度O(n2),提交超时。而求最长回文的manacher算法时间复杂度是O(n)。
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; }};
0 0
- Leetcode242: Shortest Palindrome
- Shortest Palindrome
- Shortest Palindrome
- Shortest Palindrome
- Shortest Palindrome
- ***Shortest Palindrome
- Shortest Palindrome
- Shortest Palindrome
- Shortest Palindrome
- leetcode242
- leetcode 214: Shortest Palindrome
- Leetcode214-Shortest Palindrome
- leetcode - Shortest Palindrome
- LeetCode Shortest Palindrome
- Shortest Palindrome(KMP)
- 【回文】leetcode - Shortest Palindrome
- Shortest Palindrome Leetcode Java
- Shortest Palindrome leetcode-java
- Cocos2d-x 资源加载进度条
- 2015年第六届蓝桥杯C/C++程序设计本科B组省赛 移动距离(编程大题)
- Jboss 使用bcprov注意事项
- 抽屉效果
- C++ 文件结束符
- Leetcode242: Shortest Palindrome
- Linux CentOs 7.0 mysql 5.7.10 开机自动启动方法
- QuickLook(简介)
- 深入了解Office 2016 for Mac的定制、安配置和激活
- 21行python代码实现拼写检查器
- IOS之基础控件(一)
- HttpClient容易忽视的细节——连接关闭
- java练习题---String类之求给定字符串中大小写字母的个数
- [从头学数学] 第61节 除数是两位数的除法