Uva 673 balanced parentheses

Uva 673 balanced parentheses

Subject description:

Ideas:

Is the common problem of matching brackets, with a stack to simulate the operation. Caveats, there is an input case is empty, so do not use cinto read, but with getline.

Code:

#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";
    }
}

Guess you like

Origin www.cnblogs.com/patrolli/p/11291083.html