Problem I: STL——括号匹配

来源:互联网 发布:户外网络摄像机 编辑:程序博客网 时间:2024/04/28 20:43

Description

给出一堆括号,看其是否匹配,例如 ()、()()、(()) 这样的括号就匹配,
      )(、)()) 而这样的括号就不匹配

Input

每一行代表一组测试样例,每组测试样例只包含'('和')',样例长度不超过100个字符

Output

如果所有的括号都匹配,那么输出YES,否则输出NO

Sample Input

())(

Sample Output

YESNO

HINT

使用STL的stack容易实现。


#include <iostream>#include <stack>#include <cstdio>#include <string>#include <cstring>#include <iomanip>using namespace std;int main(){    string a;    while(cin>>a){       int len=a.size();stack<char> s;       for(int i=0;i<len;i++){          if(s.empty())             s.push(a[i]);          else if(a[i]==')'){             if(s.top()=='(')                s.pop();          }          else             s.push(a[i]);       }    if(s.empty())       cout<<"YES"<<endl;    else       cout<<"NO"<<endl;    while(!s.empty())       s.pop();    }}


0 0
原创粉丝点击