PTA——最长对称子串

PTA

7-64 最长对称子串

 1 //流程:
 2 //数组存储字符串,指针i从头遍历
 3 //str[i-2]==str[i],若相等则记录对称串的长度,同时指针j从i-2开始向后遍历
 4 //两个指针所指内容不相等时停止遍历,更新对称串的长度
 5 //奇数情况// 
 6 //变量:
 7 //字符数组str
 8 //指针i、j
 9 //状态变量sys——当前对称串是否在增长 
10 //temp——当前对称串长度 
11 // lng——当前最长对称串长度
12 //细节:
13 //i从2开始遍历,按照sys的状态分两种情况
14 //若sys==1,判断str[i]==str[j],若是则temp+=2,j--;若否或j<0则sys=0,跳出
15 //若sys==0,判断str[i]==str[i-2],若是则sys=1,j--
16 //更新lng
17 //边界:
18 // 
19 //调试:
20 //aba 3
21 //abcba 5
22 //ababa 5
23 //a a 3
24 //偶数情况// 
25 
26 //奇偶切换//
27  
28 //性能优化// 
29  
30 #include<stdio.h>
31 #include<string.h>
32 #define N 1001
33 
34 int main() {
35     char str[N];
36     int len;
37     gets(str);//scanf()无法识别空格 
38     len=strlen(str);
39     int i=0,j=0,sys=0,lng=0,temp=0;
40     for(i=2; i<len; i++) {
41         if(sys==0) {
42             j=i-2;
43             if(str[j]==str[i]) {
44                 sys=1;temp=3;j--;
45                 if(j<0) sys=0;
46             }
47         } else {
48             if(str[j]==str[i] && j>=0) {
49                 temp+=2;j--; 
50             } else {
51                 sys=0;
52             }
53         }
54         if(temp>lng) lng=temp;
55     }
56     sys=0;temp=0;
57     for(i=1; i<len; i++) {
58         if(sys==0) {
59             j=i-1;
60             if(str[j]==str[i]) {
61                 sys=1;temp=2;j--;
62                 if(j<0) sys=0;
63             }
64         } else {
65             if(str[j]==str[i] && j>=0) {
66                 temp+=2;j--; 
67             } else {
68                 sys=0;
69             }
70         }
71         if(temp>lng) lng=temp;
72     }
73     printf("%d",lng);
74 }

猜你喜欢

转载自www.cnblogs.com/cxc1357/p/10823078.html
今日推荐