首页 > 解决方案 > 括号检查器 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();
}

标签: c++stack

解决方案


我改成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();
}

推荐阅读