题目:
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.
思路:经典的回文问题,中心扩展,考虑奇偶两种情况。O(n)算法见 http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html.
class Solution {
public:
string longestPalindrome(string s) {
int max_len = INT_MIN;
string result = "";
for (int i = 0; i < (int)s.size(); ++i) {
// odd length
for (int j = 0; i - j >= 0 && i + j < (int)s.size(); ++j) {
if (s[i-j] != s[i+j]) break;
if (j * 2 + 1 > max_len) { //update
max_len = j * 2 + 1;
result = s.substr(i - j, j * 2 + 1);
}
}
// even length
for (int j = 0; i - j >= 0 && i + 1 + j < (int)s.size(); ++j) {
if (s[i-j] != s[i+1+j]) break;
if (j * 2 + 2 > max_len) { //update
max_len = j * 2 + 2;
result = s.substr(i - j, j * 2 + 2);
}
}
}
return result;
}
};
总结:每个字符作为中心展开,展开过程中最多访问n个字符,复杂度为O(n^2).