2020牛客寒假算法基础集训营4 B:括号序列

B : 括号序列

2020牛客寒假算法基础集训营4 B:括号序列_第1张图片

考察点 : 栈
坑点 :   只有栈空时才是合法的

Code:

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

string str;
stackstacks;

int main(void) {
    cin >> str;
    bool flag = true;
    for(int i = 0; i < str.length(); i ++) {
        if(stacks.size() == 0) {
            stacks.push(str[i]);
            continue;
        }
        if(str[i] == '(' || str[i] == '{' || str[i] == '[') {
            stacks.push(str[i]);
        } else if(str[i] == ')' && stacks.top() == '(' && stacks.size() != 0) {
            stacks.pop();
        } else if(str[i] == '}' && stacks.top() == '{' && stacks.size() != 0) {
            stacks.pop();
        } else if(str[i] == ']' && stacks.top() == '[' && stacks.size() != 0) {
            stacks.pop();
        } else {
            flag = false;
            break;
        }
    }
    if(flag && stacks.size() == 0) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}

你可能感兴趣的:(2020牛客寒假算法基础集训营4 B:括号序列)