NYOJ-2 括号配对问题 -- 数据结构_堆栈

以前做过的,现在整理一下,主要是堆栈的使用

1.碰到左括号就入栈,碰到右括号就从栈里弹出一个和当前比配,匹配失败就肯定是NO了;

2.如果右括号弹栈的时候栈空,则说明之前没有和右括号匹配的左括号了,这结果也是NO;

3.如果字符串处理完了栈里面还有符号,结果为NO;

如果处理到最后都没有出现NO的情况,则输出YES;

注意两种括号要区别开

#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std; stack<char> stack_ch; int main()
{
int num;
char ch;
int flag;
cin>> num;
getchar();
while(num--)
{
flag = 0;
while(!stack_ch.empty ())
{
stack_ch.pop();
}
while((ch = getchar()) != '\n')
{
if(ch == '[')
stack_ch.push (ch);
else if(ch == '(')
stack_ch.push (ch);
else if(ch == ']')
{
if(stack_ch.empty())
flag =1 ;
else if(stack_ch.top() == '[')
stack_ch.pop ();
else
flag = 1;
}
else if(ch == ')')
{
if(stack_ch.empty ())
flag = 1;
else if(stack_ch.top() == '(')
stack_ch.pop();
else
flag = 1;
}
}
if(flag == 1)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
}
return 0;
}

  

上一篇:ASP.NET 各种缓存


下一篇:Browserify: 使nodejs模块可以在浏览器下使用