Uva 673 Parentheses Balance

题意:判断一个是否是合法的,此式子合法的条件是:

    1.空串是合法的

    2.如果A和B都是合法的, 那么AB也是合法的

    3.如果A是合法的,那么(A)和[A]也是合法的

思路:

  可以用堆栈的方法,如果读入一个左符号,则压栈,反之,从栈中弹出一个符号,如果是对应的左符号,则继续,如果不能,则此表达式不合法。

  需要注意的是:输入数据可能是空串,所以得到空串时,也需要输出合法的答案

  

/*

    UvaOJ 673

    Emerald

    Mon 1 Jun 2015

*/

#include <iostream>

#include <cstring>

#include <cstdio>

#include <stack>



using namespace std;



bool IsValid( string &str ) {

    stack <char> st;

    int length = str.length();

    for( int i=0; i < length; i ++ ) {

        if( str[i] == '(' || str[i] == '[' ) {

            st.push( str[i] );

        } else if( st.empty() ) {

            return false;

        } else {

            if( ( str[i]==')' && st.top() == '(' ) || ( str[i]==']' && st.top() == '[' ) ) {

                st.pop();

                continue;

            } else {

                return false;

            }

        }

    }

    return st.empty();

}



int main() {

    int T;

    while(cin >> T) {

        cin.get();

        while( T -- ) {

            string str;

            getline( cin, str );

            printf("%s\n", IsValid( str ) ? "Yes" : "No" );

        }

    }

    return 0;

}

 

你可能感兴趣的:(uva)