一、字符串篇
5. 最长回文子串(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。
提示1:How can we reuse a previously computed palindrome to compute a larger palindrome?
提示2:If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome?
提示3:
Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
方法一、暴力解法:
只需记录最长回文子串的下标和字符串的长度即可、枚举的时候只需要枚举那些长度大于等于2并且超过最长长度的那些串即可,因此左边界只需要枚举到倒数第二个位置,右边界从左边界加1的地方开始枚举,
C++ 超出时间限制
代码如下:
class Solution {
public:
string longestPalindrome(string s) {
if(s.length()<2) {
return s;
}
int str_len = s.length();
int str_begin = 0;
int max_length = 1;
for(int i=0; i < str_len-1; i++) {
int j = i+max_length;
for( ; j<str_len; j++) {
if(validPalindrome(s,i,j)){
str_begin = i;
max_length = j-i+1;
}