典型的栈的应用,思路很简单,先整行输入字符串,然后从左往右开始依次遍历每个字符,如果是左括号便压人栈中,如果是右括号便弹出栈顶左括号(左右抵消),遇到B字符则遍历结束,输出栈中元素个数既是问题的解,代码如下:(写了栈类,代码稍长,因为是专题训练,不然就直接用STL了)
#include <iostream>
#include <cstdlib>
using namespace std;
typedef char anytype;
struct stacks
{
struct node //链栈
{
anytype data;
struct node *next;
}*head;
stacks() //构造函数
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
}
bool empty() //判断空栈
{
if(head->next)
return false;
return true;
}
void push(anytype n) //入栈
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=head->next;
head->next=p;
}
void pop() // 出栈
{
struct node *p;
p=head->next;
if(p)
{
head->next=p->next;
free(p);
}
}
anytype top() //查询栈顶元素
{
if(!empty())
return head->next->data;
return 0;
}
int counts() //返回栈内元素数量
{
struct node *p;
int res=0;
p=head->next;
while(p)
{
res++;
p=p->next;
}
return res;
}
};
int main()
{
ios::sync_with_stdio(false);
string str;
while(getline(cin,str,'\n'))
{
stacks s;
int len=str.length();
for(int i=0;i<len;i++)
{
if(str[i]=='(') //左括号入栈
s.push(str[i]);
else if(str[i]==')') //右括号则弹出栈顶元素
s.pop();
else if(str[i]=='B') //B则结束
break;
}
cout<<s.counts()<<endl; //输出栈内元素
}
return 0;
}