标签:
问题链接:https://leetcode.com/problems/longest-palindromic-substring/
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
采用Manacher算法求字符串的最大回文子串, 暴力方法时间复杂度为O(n^3),效率太低。
Manacher算法介绍:http://www.open-open.com/lib/view/open1419150233417.html
在网上找了几个版本,这个文章介绍的比较清楚,其实原理很简单,开始看的时候有点绕。
c++ 8ms
class Solution { public: string longestPalindrome(string s) { string replace; int i = 0; int *radius, extend = 0, cen = 0, max_substr = 0, start_substr = 0; replace += "@"; replace += "#"; for (i = 0;i < s.size();++i) { replace += s[i]; replace += "#"; } replace += "\0"; radius = new int[replace.size()]; memset(radius, 0, replace.size()*sizeof(int)); for (i = 1;i < replace.size();++i) { if (extend >= i) radius[i] = ((extend -i) > radius[2*cen - i])?radius[2*cen - i]:(extend - i); else radius[i] = 1; while (replace[i - radius[i]] == replace[i + radius[i]]) ++radius[i]; --radius[i]; if (radius[i] + i > extend) { cen = i; extend = radius[i] + i; } if (radius[i] > max_substr) { max_substr = radius[i]; start_substr = (i - 1)/2 - max_substr/2; } } delete []radius; return s.substr(start_substr, max_substr); } };
标签:
原文地址:http://my.oschina.net/u/2313065/blog/523824