算法13:检查一个表达式中的括号是否合法,括号包括 {, [, (, ), ], }

算法分析

考查栈的应用。遍历表达式,如果是左括号,进栈;如果是右括号,则与栈顶元素比较,匹配则出栈,否则不合法。遍历完表达式,如果是空栈,则说明表达式是合法的。

c++代码

bool JudgeExpression(const char* expression,int length)
{
    bool isLegal = false;

    stack<char> bracketsStack;
    //如果是左括号,则进栈;如果是右括号,则与栈顶元素比较,匹配则出栈,否则返回false
    for(int i = 0; i < length; i++)
    {
        if(expression[i]== '(' || expression[i] == '[' || expression[i] == '{')
        {
            bracketsStack.push(expression[i]);
        }

        if(expression[i] == ')')
        {
            if(!bracketsStack.empty() && bracketsStack.top() == '(')
            {
                bracketsStack.pop();
            }
            else
            {
                isLegal = false;
                break;
            }
        }
        else if(expression[i] == ']')
        {
            if(!bracketsStack.empty() && bracketsStack.top() == '[')
            {
                bracketsStack.pop();
            }
            else
            {
                isLegal = false;
                break;
            }
        }
        else if(expression[i] == '}')
        {
            if(!bracketsStack.empty() && bracketsStack.top() == '{')
            {
                bracketsStack.pop();
            }
            else
            {
                isLegal = false;
                break;
            }
        }
    }

    //如果栈为空,说明匹配成功了
    if(bracketsStack.empty())
    {
        isLegal = true;
    }

    return isLegal;
}

测试代码

int _tmain(int argc, _TCHAR* argv[])
{
    string expression1 = "(5-4)+{[2*(5-3*4)-8]*2}";
    bool isLegal = JudgeExpression(expression1.c_str(),expression1.length());

    cout<<"(5-4)+{[2*(5-3*4)-8]*2} isLegal = "<"(5-4)+{[2*(5-3*4]-8)*2}";
    isLegal = JudgeExpression(expression2.c_str(),expression2.length());

    cout<<"(5-4)+{[2*(5-3*4]-8)*2} isLegal = "<return 0;
}

你可能感兴趣的:(C++,算法)