题目: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.
分析:这是一个求最长对称子串的问题,最容易想到的直接解法就是从头开始,以两个字符中间位置或者某一个字符作为中心,向两边进行扩展。在最坏情况下(例如输入的字符串每个位置都是同一个字符),每次扩展时需要的比较次数为1,2,3,…n/2…3,2,1,算法的时间复杂度为 O(n2) .
#include <utility>
#include <string>
#include <iostream>
using std::pair;
using std::string;
using std::cout;
using std::endl;
class Solution {
public:
int length, max_length, size;
int i, j, k;
pair<int, int> section;
void scan(int j, int k, string &s) {
while (j >= 0 && k <= size - 1) {
if (s[j] == s[k]) {
length += 2;
j--;
k++;
} else {
break;
}
}
if (length > max_length) {
max_length = length;
section.first = j + 1;
section.second = k - 1;
}
}
string longestPalindrome(string s) {
max_length = 0;
size = s.size();
for (i = 0; i < size; i++) {
j = i;
k = i + 1;
length = 0;
scan(j, k, s);
length = 1;
j = i - 1;
scan(j, k, s);
}
string result;
for (i = section.first; i <= section.second; i++)
result += s[i];
return result;
}
};
另一种比较巧妙的算法是Manacher’s Algorithm 。与前一个算法相比,它利用了对称子串的对称特性,减少了很多次不必要的比较。这个算法的构思比较巧妙,可以达到 O(n) 的时间复杂度。有兴趣的读者可以参考上面的网站,已有清晰的讲述,这里不再赘述。