1153:括号匹配问题

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<stack>
 5 using namespace std;
 6 
 7 typedef struct  
 8 {
 9     char ch;
10     int pos;
11 }Symbol;
12 int main()
13 {
14     char s[100],flag[100];
15     stack<Symbol> st;
16     while(cin.getline(s,100))
17     {
18         memset(flag,0,sizeof(flag));
19         int i,len=strlen(s);
20         Symbol t;
21         for(i=0;i<len;++i)
22         {
23             
24             if(s[i]=='(')
25             {
26                 t.ch=s[i];
27                 t.pos=i;
28                 st.push(t);
29             }
30             else if(s[i]==')')
31             {
32                 if(!st.empty())
33                 {
34                     t=st.top();
35                     if(t.ch!='(')
36                     {
37                         flag[i]='?';
38                     }
39                     else
40                     {
41                         st.pop();
42                     }
43                 }
44                 else
45                     flag[i]='?';
46             }
47         }
48         while(!st.empty())
49         {
50             t=st.top();
51             if(t.ch=='(')
52                 flag[t.pos]='$';
53             else
54                 flag[t.pos]='?';
55             st.pop();
56         }
57         cout<<s<<endl;
58         
59         for(i=0;i<len;++i)
60         {
61             if(flag[i]=='$'||flag[i]=='?')
62                 cout<<flag[i];
63             else
64                 cout<<' ';
65         }
66         cout<<endl;
67     }
68     return 0;
69 }

 

posted @ 2012-04-13 17:30  dupuleng  阅读(107)  评论(0)    收藏  举报