Problem C: STL——括号匹配
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 4075 Solved: 2532
[Submit][Status][Web Board]
Description
给出一堆括号,看其是否匹配,例如 ()、()()、(()) 这样的括号就匹配,
)(、)()) 而这样的括号就不匹配
Input
每一行代表一组测试样例,每组测试样例只包含'('和')',样例长度不超过100个字符
Output
如果所有的括号都匹配,那么输出YES,否则输出NO
Sample Input
()
)(
Sample Output
YES
NO
HINT
使用STL的stack容易实现。
Append Code
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string temp;
while(cin>>temp)
{
stack<int> arr;
int l=temp.length();
if(l%2==1||temp[0]==')'||temp[l-1]=='(')
cout<<"NO"<<endl;
else
{
for(int i=0; i<l; i++)
{
if(temp[i]=='(')
arr.push(1);
else if(temp[i]==')'&&arr.empty()!=0)//(()) 型
arr.pop();
else//()))型
{
break;
}
}
if(temp.empty()==0&&i==l)//为空,并且正常完成循环
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
}