首页 > 其他 > 详细

uva673-括号平衡

时间:2016-08-08 00:42:49      阅读:143      评论:0      收藏:0      [点我收藏+]

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

 

翻译请戳 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;
    }
}

 

uva673-括号平衡

原文:http://www.cnblogs.com/ZengWangli/p/5747761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!