673 - Parentheses Balance (UVA)

题目链接如下:

Online Judge

这道题我开始用递归做,结果TLE......一时没头绪,昨天晚上散步时候才想到用栈就能简单解决.....

AC代码如下:

#include 
#include 
// #define debug

int n;
std::string str;

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    scanf("%d\n", &n);
    while (n--){
        getline(std::cin, str);
        if (str.size() % 2 || str[0] == ']' || str[0] == ')' || str.back() == '[' || str.back() == '('){
            printf("No\n");
            continue;
        }
        std::string stk;
        for (int i = 0; i < str.size(); ++i){
            if (!stk.empty() && ((stk.back() == '(' && str[i] == ')') || (stk.back() == '[' && str[i] == ']'))){
                stk.pop_back();
            } else {
                stk.push_back(str[i]);
            }
        }
        printf("%s\n", stk.empty() ? "Yes" : "No");
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}

你可能感兴趣的:(UVA,算法)