愚人节的礼物

本文介绍了如何使用栈和数组两种数据结构来解决HDU 1870编程题。通过栈模拟实现,运行时间为15毫秒;而采用数组模拟则达到了0毫秒的高效性能。这两种方法都用于处理输入字符串中的括号匹配问题,并计算最终未匹配的左括号数量。

http://acm.hdu.edu.cn/showproblem.php?pid=1870

栈模拟:15MS

View Code
 1 #include<iostream>
 2 #include<stack>
 3 #include<cstring>
 4 using namespace std ;
 5 char a[1005] ;
 6 stack<char>s ;
 7 int main()
 8 {
 9     while(cin>>a)
10     {
11         while(!s.empty())
12         s.pop() ;
13         int len = strlen(a) ;
14         for(int i=0; i<len; i++)
15         {
16             if(a[i]=='B')
17             {
18                 cout<<s.size()<<endl ;
19                 break ;
20             }
21             if(a[i]=='(')
22             s.push(a[i]) ;
23             if(a[i]==')')
24             s.pop() ;
25         }
26     }
27     return 0 ;
28 }

数组模拟:0MS

View Code
 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std ;
 4 int main()
 5 {
 6     char a[1005] ;
 7     while(cin>>a)
 8     {
 9         int count = 0 ;
10         int len = strlen(a) ;
11         for(int i=0; i<len; i++)
12         {
13             if(a[i]=='(')
14             count++ ;
15             else
16             if(a[i]==')')
17             count-- ;
18             else
19             break ;
20         }
21         cout<<count<<endl ;
22     }
23     return 0 ;
24 }

 

 

转载于:https://www.cnblogs.com/yelan/archive/2013/03/24/2979925.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值