【回文】leetcode - Shortest Palindrome
2017-04-22 16:58
267 查看
题目:
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; } } };
相关文章推荐
- [LeetCode] Palindrome Pairs 回文对
- 【leetcode】对撞指针应用之回文字符串判断(忽略大小写,以及出数字外其他字符)
- [C++]LeetCode: 99 Longest Palindromic Substring (最长回文子串)
- [LeetCode 132] - 回文分割II(Palindrome Partitioning II)
- (LeetCode)Palindrome Linked List --- 单链表回文
- 刷leetcode第五题-最长回文字符串
- Leetcode 131 Palindrome Partitioning 回文分割
- leetcode第9题,判断数字是否是回文数字的两种方法
- LeetCode 5 : Longest Palindromic Substring ---- 最长回文
- LeetCode 9 Palindrome Number 回文数字
- LeetCode 131. Palindrome Partitioning(回文分区)
- LeetCode: Palindrome 回文相关题目
- LeetCode 214. Shortest Palindrome(最短回文)
- 【LeetCode刷题】最长回文子串Longest Palindromic Substring(java)
- leetCode 9.Palindrome Number (回文数字) 解题思路和方法
- 每天一道leetcode234-回文链表
- leetcode5 最长回文子串
- LeetCode 9 Palindrome Number(回文数字判断)
- leetcode-java.T005_LongestPalindromicSubstringTotal 给定一个字符串S,找出它的最大的回文子串
- 【回文】leetcode - Shortest Palindrome