uva673-括号平衡

小白书里数据结构基础的训练参考

 

翻译请戳 http://luckycat.kshs.kh.edu.tw/

 

解题思路

嗯。。。就是用栈。

出栈的时候不匹配、最后栈非空都是非法的表达式。

 

代码

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<stack>
using namespace std;
const int MAX_LEN = 128+1;
int main()
{
    char operStr[MAX_LEN];
    int numStr;
    cin >> numStr;
    getchar();
    for(int i=0; i<numStr; i++) {
        stack<char> s;
        bool flag = true;
        gets(operStr);
        for(int j=0; j<strlen(operStr); j++) {
            if(operStr[j] == '(' || operStr[j] == '[') s.push(operStr[j]);
            else {
                if(operStr[j] == ']' && (s.empty() || !s.empty() && s.top() != '[')) {
                    flag = false; break;
                }
                if(operStr[j] == ')' && (s.empty() || !s.empty() && s.top() != '(')) {
                    flag = false; break;
                }
                s.pop();
            }
        }
        if(s.empty() && flag) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
}

 

posted @ 2016-08-08 00:02  啊嘞  阅读(273)  评论(0编辑  收藏  举报