其他分享
首页 > 其他分享> > Uva 673平衡的括号

Uva 673平衡的括号

作者:互联网

Uva 673平衡的括号

题目描述:

思路:

就是普通的括号匹配问题,用栈来模拟操作。需要注意的地方是,有输入为空的情况,所以不要用cin来读取,而是用getline

代码:

#include <iostream>
#include <stack>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    //freopen("uva673_in.txt", "r", stdin);
    //freopen("uva673_out.txt", "w", stdout);
    string s;
    getline(cin, s);
    stringstream ss(s);
    int n ; ss >> n;
    while(n--){
        string s; getline(cin, s);  
        stack<char> res;
        int failed = 0;
        for(int i = 0; i < s.length(); ++i){
            if(s[i] == ')'){
                if(!res.empty()) {
                    char c = res.top();
                    if(c == '(') res.pop();
                    else { failed = 1; break;}
                }
                else { failed = 1; break;} 
            }else if(s[i] == ']'){
                if(!res.empty()){
                    char c = res.top();
                    if(c == '[') res.pop();
                    else { failed = 1; break;}
                }
                else { failed = 1; break;}
            }
            else res.push(s[i]);
        }
        if(res.empty() && !failed) cout << "Yes\n";
        else cout << "No\n";
    }
}

标签:include,failed,int,res,else,break,括号,Uva,673
来源: https://www.cnblogs.com/patrolli/p/11291083.html