HDU 1870 愚人节的礼物

看到括号匹配当然想到栈了。

int main()
{
    string s;
    while(cin>>s)
    {
        stack<char> stk;
        for(int i=0;i<s.size();i++)
        {
            if(s[i] == '(') stk.push(s[i]);
            else if(s[i] == ')') stk.pop();
            else break;
        }
        cout<<stk.size()<<endl;
    }
    //system("pause");
    return 0;
}

数据已经保证每个透视图画的都是合法的了,所以求一下左边有多少个落单的左括号或者求一下右边有多少个落单的右括号。

int main()
{
    string s;
    while(cin>>s)
    {
        int res=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i] == '(') res++;
            else if(s[i] == ')') res--;
            else break;
        }
        cout<<res<<endl;
    }
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/fxh0707/p/14619082.html