题意:对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?
,最长对称子串为s PAT&TAP s
,于是你应该输出11。
思路:分成两种情况:对称子串是奇数和对称子串是偶数。如果是奇数一开始的cnt设置为1,如果是偶数,cnt为2。
一开始自己写一直有个样例过不去(。。还不知道是为啥

1 #include <iostream> 2 #include<string> 3 4 using namespace std; 5 6 int main() 7 { 8 int ma=0,cnt=1,b,a; 9 string s; 10 getline(cin,s); 11 for(int i = 1; i < s.size()-1; i ++) 12 { 13 b = i - 1; 14 a = i + 1; 15 16 cnt = 1; 17 while(s[b]==s[a]&&b>=0&&a<s.size()) 18 { 19 cnt+=2; 20 b--; 21 a++; 22 } 23 24 if(ma < cnt) 25 ma = cnt; 26 } 27 cnt = 0; 28 for(int i = 0; i < s.size()-1; i ++) 29 { 30 if(s[i]==s[i+1]) 31 { 32 cnt = 2; 33 b = i - 1; 34 a = i + 2; 35 while(s[b]==s[a]&&b>=0&&a<s.size()) 36 { 37 cnt+=2; 38 b--; 39 a++; 40 } 41 42 } 43 44 if(ma < cnt) 45 ma = cnt; 46 47 } 48 cout<<ma<<endl; 49 50 return 0; 51 }
看了别人的做法之后改了一下
1 #include <iostream> 2 #include<string> 3 4 using namespace std; 5 6 int main() 7 { 8 int ma=0,cnt=0,b,a; 9 string s; 10 getline(cin,s); 11 for(int i = 0; i < s.size(); i ++) 12 { 13 cnt = 1;//注意的地方 14 for(int j = 1; i + j < s.size()&&i-j>=0; j++) 15 { 16 if(s[i-j]!=s[i+j])break; 17 cnt += 2; 18 } 19 if(ma < cnt)ma=cnt; 20 cnt = 0; 21 for(int j = 0;j+i+1<s.size()&&i-j>=0;j++) 22 { 23 if(s[i-j]!=s[i+j+1])break; 24 cnt+=2; 25 } 26 if(ma < cnt)ma=cnt; 27 } 28 cout<<ma<<endl; 29 30 return 0; 31 }