第六章部分例题

6-4 自己先敲了一遍虽然可以完成书上的功能但是漏洞百出

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 const int maxn=100000+100;
 8 
 9 char txt[maxn];
10 int next[maxn];
11 
12 int main()
13 {    
14     while(scanf("%s",txt+1)==1)
15     {    
16         int len=strlen(txt)-1;
17         int start=1;
18 
19         for(int i=0;i<=len;i++)
20         {
21             next[i]=i+1;
22         }
23 
24         for(int i=1;i<=len;i++)
25             if(txt[i]!='[' && txt[i]!=']')
26             {
27                 start=i;
28                 break;
29             }
30 
31         int pre;
32         int behind;
33 
34         for(int i=1;i<=len;i++)
35         {
36             if(txt[i]=='[')
37             {
38                 pre=i-1;
39                 next[0]=i;
40             }
41 
42             if(txt[i]==']')
43             {
44                 next[i]=start;
45                 behind=i+1;
46             }
47         }
48 
49         next[pre]=behind;
50 
51 
52         for(int i=next[0];i!=0;i=next[i])
53         {
54             if(txt[i]!='[' && txt[i]!=']')
55                 printf("%c",txt[i]);
56         }
57 
58         printf("
");
59 
60     }
61 
62 }
View Code

书上的过程就是模仿光标的过程

 1 const int maxn=100000+100;
 2 
 3 char txt[maxn];
 4 int next[maxn];
 5 
 6 
 7 
 8 int main()
 9 {
10     
11 
12     while(scanf("%s",txt+1)==1)
13     {
14 
15         memset(next,0,sizeof(next));              //必要,为了清空next数组,防止上一次的影响
16 
17         int len=strlen(txt+1);
18 
19         int cur=0;
20         int last=0;
21 
22         for(int i=1;i<=len;i++)
23         {
24             if(txt[i]=='[')
25                 cur=0;
26             else if(txt[i]==']')
27                 cur=last;
28             else
29             {
30                 next[i]=next[cur];
31                 next[cur]=i;
32 
33                 if(cur==last) last=i;
34 
35                 cur=i;
36             }
37         }
38 
39         for(int i=next[0];i!=0;i=next[i])
40             printf("%c",txt[i]);
41 
42         printf("
");
43     }
44 
45     return 0;
46 }

做了这一题之后略有感悟,第一是  核心代码22行到37行这样写并不是巧合,我认为代码这样写出来是巧合是因为自己的理解还不够

第二  对比我之前的写的代码,书上的代码是根据模仿光标的思路来写的,这样才是题意,比我自己瞎想的方法不知道高到哪里去了.

Yosoro
原文地址:https://www.cnblogs.com/tclan126/p/7236859.html