括号检查器C ++程序

问题描述

我正在学习处理堆栈并尝试实现一些问题。我将极客的算法用于极客。在此括号检查程序中。对于输入{{[[])},这将返回false 有人可以帮忙为什么。

bool ispar(string x)
{
    // Your code here
    stack<int> s;
    
    for(int i=0;i<x.size();i++){
        if(x[i]=='{' || x[i]=='[' || x[i]=='('){
            s.push(x[i]);
            continue;
        }
        if(s.empty()){
            return false;
        }
        switch(x[i]){
            case ')':{
                x = s.top();
                s.pop();
                if (x[i]=='{' || x[i]=='[') 
                    return false;
                break;
            }
            case '}':{
                x = s.top();
                s.pop();
                if(x[i] =='[' || x[i]=='(')
                    return false;
                break;
            }
            case ']':{
                x = s.top();
                s.pop();
                if(x[i] == '(' || x[i] =='{')
                    return false;
                break;
            }
        }
    }
    return s.empty();
}

解决方法

我将stack<int>更改为stack<char>,并且必须将s.top()分配给char,而不是string x

bool ispar(const std::string& x)
{
    // Your code here
    stack<char> s;
    char opening_char;

    for (int i = 0; i < x.size(); i++) {
        if (x[i] == '{' || x[i] == '[' || x[i] == '(') {
            s.push(x[i]);
            continue;
        }

        if (s.empty()) {
            return false;
        }

        switch (x[i]) {
        case ')': {
            opening_char = s.top();
            s.pop();
            if (x[i] == '{' || x[i] == '[')
                return false;
            break;
        }
        case '}': {
            opening_char = s.top();
            s.pop();
            if (x[i] == '[' || x[i] == '(')
                return false;
            break;
        }
        case ']': {
            opening_char = s.top();
            s.pop();
            if (x[i] == '(' || x[i] == '{')
                return false;
            break;
        }
        }
    }

    return s.empty();
}