题目描述:给定一个字符串,求它的最长回文子串(子串是连续的)的长度
解法一:枚举法
外面的双层for循环确定连续子串头尾,加上里面的一个for循环来判断该子串是否为回文串,此外用一个max变量(初始值为1)动态更新保存最长子回文串的长度,时间复杂度为O(n^3),空间复杂度为O(1)。
#include <iostream>
#include <string>
using namespace std;
bool IsPalindrome(string &str, int start, int end){
while(start < end){
if(str[start] != str[end])
return false;
++start;
--end;
}
return true;
}
int LongestPalindrome(string &str){
if(str.size() == 0)
return 0;
int len = str.size(), i, j, maxLen = 1;
for(i = 0; i < len; ++i){
for(j = i+1; j < len; ++j){
if(IsPalindrome(str, i, j))
if(maxLen < j-i+1)
maxLen = j-i+1;
}
}
return maxLen;
}
int main(){
string str;
while(cin >> str){
cout << LongestPalindrome(str) <<


369

被折叠的 条评论
为什么被折叠?



