括号匹配

   匹配情况:(),{},[],{[()]}

   (1)使用C++中的STL写括号匹配 

   代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #include<stack>
 5 #include<algorithm>
 6 using namespace std;
 7 stack<char>s;
 8 bool judge( char c)
 9 {
10  switch (c)
11  {
12  case '[':
13  case '{':
14  case '(':
15   return true;
16  default:
17   return false;
18  }
19 }
20 
21 char match( char c)
22 {
23  switch(c)
24  {
25  case '{':
26   return '}';
27  case '[':
28   return ']';
29  case '(':
30   return ')';
31  }
32 }
33 
34 int main()
35 {
36   char str[100];
37   scanf("%s",str);
38   while(!s.empty())
39     s.pop();
40   
41   printf("匹配成功的部分:\n");
42   int i;
43   for(i=0;i<strlen(str);i++)
44   {
45       if(judge(str[i]))
46         s.push(str[i]);
47       else
48       {
49         if(str[i]==match(s.top()))
50       {
51           printf("%c%c",s.top(),str[i]);
52           s.pop();
53       }
54       else
55       {
56           printf("\n匹配出现错误的地点:\n");
57           printf("%c-%c\n",s.top(),str[i]);
58           break;
59       }    
60     }
61   }
62   if(s.empty())
63     printf("\n匹配成功!\n");
64   else
65   {
66       printf("未匹配成功的内容:\n");
67       while(!s.empty())
68     {
69         printf("%c",s.top());
70         s.pop();
71     }
72     printf("\n");
73     for(;i<strlen(str);i++)
74      if(!judge(str[i]))
75       printf("%c",str[i]);
76       printf("\n"); 
77   }
78   return 0;    
79 } 
View Code

    (2)使用数组代替STL中的函数

    注意栈为空时的情况为top==-1,入栈时,先top++,再保存数据s[top]=e;出栈时,先取数据e=s[top],再top--。

    代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #include<algorithm>
 5 using namespace std;
 6 char s[100]; 
 7 bool judge( char c)
 8 {
 9  switch (c)
10  {
11  case '[':
12  case '{':
13  case '(':
14   return true;
15  default:
16   return false;
17  }
18 }
19 
20 char match( char c)
21 {
22  switch(c)
23  {
24  case '{':
25   return '}';
26  case '[':
27   return ']';
28  case '(':
29   return ')';
30  }
31 }
32 
33 int main()
34 {
35   char str[100];
36   scanf("%s",str);
37   memset(s,'\0',sizeof(s));
38   int i;
39   int top=-1;
40   printf("匹配成功的部分:\n"); 
41   for(i=0;i<strlen(str);i++)
42   {
43       if(judge(str[i]))
44       {
45         top++;
46         s[top]=str[i];
47     }
48       else
49       {
50         if(str[i]==match(s[top]))
51       {
52           printf("%c%c",s[top],str[i]);
53           top--;
54       }
55       else
56       {
57           printf("\n匹配出现错误的地点:\n");
58           printf("%c-%c\n",s[top],str[i]);
59           break;
60       }    
61     }
62   }
63   if(top==-1)
64     printf("\n匹配成功!\n");
65   else
66   {
67       printf("未匹配成功的内容:\n");
68       while(top!=-1)
69     {
70         printf("%c",s[top]);
71         top--;
72     }
73     printf("\n");
74     for(;i<strlen(str);i++)
75       if(!judge(str[i]))
76       printf("%c",str[i]);
77       printf("\n"); 
78   }
79   return 0;    
80 } 
View Code

 

posted @ 2016-07-03 16:59  太过随意  阅读(157)  评论(1)    收藏  举报