题目:
输入一个字符串Str,输出Str里最长回文子串的长度。
回文串:指aba、abba、cccbccc、aaaa这种左右对称的字符串。
串的子串:一个串的子串指此(字符)串中连续的一部分字符构成的子(字符)串
例如 abc 这个串的子串:空串、a、b、c、ab、bc、abc
Input
输入Str(Str的长度 <= 1000)
Output
输出最长回文子串的长度L。
Sample Input
Sample Output
思路:本题只要求最长回文子串的长度,所以从最大开始往下找,
找到每个符合当前长度的子串,判断该子串是否为回文字符串,如果是,则找到,输出当前长度,结束程序
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){ falg=1; for(int j=0;j<tlen/2;++j){ if(str[i+j]!=str[(i+tlen-1)-j]){ falg=0; break; } } if(falg){ cout<<tlen<<endl; return 0; } } tlen--; } return 0; }
|