string findLongestPalindrome(string & str){
size_t n = str.size();
size_t max_length = 0;
size_t len = 0;
size_t start = 0;
if(n <= 1){
return str;
}
for(size_t i = 0; i < n; ++i){ //start number
for(size_t j = i + 1; j < n; ++j){ // end number
size_t temp_i = 0, temp_j = 0;
for(temp_i = i, temp_j = j; temp_i < temp_j; ++temp_i, --temp_j){
if(str[temp_i] != str[temp_j]){ // if the corresponding chars are not same. begin next ++j
break;
}
if((j - i)%2 == 0){ //odd number aaaaa
if(temp_j - temp_i <= 2){
cout <<i << "->" << j <<'\n';
len = j - i + 1;
if(len > max_length){
max_length = len;
start = i;
}
}
}else{
if(temp_j - temp_i <= 1){ //even number abba
cout <<i << "-->" << j <<'\n';
len = j - i + 1;
if(len > max_length){ // only when current len is begger than last max_length
max_length = len;
start = i;
}
}
}
}
}
}
if(max_length > 0){
return str.substr(start, max_length);
}
return "";
}
普通算法,不过这个算法leetcode上超时了。