题目:

输入一个字符串Str,输出Str里最长回文子串的长度。

回文串:指aba、abba、cccbccc、aaaa这种左右对称的字符串。

串的子串:一个串的子串指此(字符)串中连续的一部分字符构成的子(字符)串
例如 abc 这个串的子串:空串、a、b、c、ab、bc、abc

Input
输入Str(Str的长度 <= 1000)
Output
输出最长回文子串的长度L。
Sample Input

1
daabaac

Sample Output

1
2
5

思路:本题只要求最长回文子串的长度,所以从最大开始往下找,
找到每个符合当前长度的子串,判断该子串是否为回文字符串,如果是,则找到,输出当前长度,结束程序

ac代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<string.h>
using namespace std;
int main(){
string str;
ios::sync_with_stdio(false);
cin>>str;
int len=str.length();//得到字符串的长度

int tlen=len;
int falg=0;
while(tlen){//最长回文子串长度,默认最大
for(int i=0;i+tlen<=len;++i){//找到 tlen长度的子串的初始下标
falg=1;//初始相同,认为当前子串是回文
for(int j=0;j<tlen/2;++j){ // 3 7 3 4 5 6 7 判断回文只需要判断 前 tlen/2个
if(str[i+j]!=str[(i+tlen-1)-j]){// 遇到不相同,进入下一个长度不变的子串
falg=0; //不是
break;//结束当前判断进入下一个判断
}
}
//找到了
if(falg){
cout<<tlen<<endl;
return 0;
}
}
tlen--;
}
return 0;
}