1. 程式人生 > >Problem C: STL——括號匹配

Problem C: STL——括號匹配

hint href tac mit emp for content CP ask

Problem C: STL——括號匹配

Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 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;
        }
    }
}

  

Problem C: STL——括號匹配