您的位置:首页 > 其它

[容易] UVa OJ 673 经典括号匹配问题

2017-09-01 10:58 246 查看
题目描述

思路:

本题就是一个简单的括号匹配问题,使用栈便可轻松解决。

具体代码:

#include <iostream>
#include <string>
#include <stack>

using namespace std;
bool isValid(string& s)
{
stack<char> sc;
for(int i=0;i<s.size();++i)
{
switch(s[i])
{
case '(':
case '[':
sc.push(s[i]);
break;
case ']':
if(sc.empty()||sc.top()!='[')
return false;
else
sc.pop();
break;
case ')':
if(sc.empty()||sc.top()!='(')
return false;
else
sc.pop();
break;
}
}
if(sc.empty())
return true;
else
return false;
}

int main()
{
//  freopen("input.txt","r",stdin);
int n;
cin>>n;
getchar();
string s;
for(int i=0;i<n;++i)
{
getline(cin,s);
if(s.empty()||isValid(s))
{
cout<<"Yes"<<endl;
}
else
cout<<"No"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  括号匹配