UVa 673 Parentheses Balance (stack)

题目描述 : 判断字符串是不是符合正确的表达式形式。

要点 : 考虑字符串为空的时候,用getline输入,每一次判断后如果为No则要清空栈。对称思想。

             注意输入格式。

代码:

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
int main()
{
    stack<int> s;
    int n;
    int value[200];
    cin>>n;
    cin.ignore();
    string str;
    while(n--)
    {
        getline(cin , str);
        int len = str.size();
        if(len == 0)
             cout<<"Yes\n";
    else
    {
        for(int i=0; i<len; i++)
        {
            if(str[i] == '(')
                value[i] = 1;
            if(str[i] == ')')
                value[i] = -1;
            if(str[i] == '[')
                value[i] = 2;
            if(str[i] == ']')
                value[i] = -2;
        }
        for(int i=0; i<len; i++)
        {
            if(s.empty())
            {
                s.push(value[i]);
            }
            else
            {
                if(s.top() == (-value[i]) && s.top()>0)
                    s.pop();
                else
                    s.push(value[i]);
            }
        }
        if(s.empty())
            cout<<"Yes\n";
        else
        {
            cout<<"No\n";
            while(!s.empty())
            {
                s.pop();
            }
        }
    }
    }
    return 0;
}




 

posted @ 2014-12-04 15:40  Pickle  阅读(326)  评论(0)    收藏  举报