C++括号匹配应用程序

FJa*_*Jam 3 c++ stack stl data-structures

我必须编写一个接受字符串并返回bool的函数.传入的字符串是ex.({[]})打开或关闭的一系列或不同的括号,并返回'parens'是否均衡.这必须通过向堆栈添加项目来实现.我收到以下错误:

parenMatching_demo.cpp:18:12:错误:'c =='(''中'运算符=='不匹配

psudocode是:

matcher(expression) 
    for each character in expression 
        if  the character is an opener
            push on stack
        else if the character is a closr
            if stack is empty return false
            if the (opener at) the top of the stack does not match the closer
                return false
            pop the stack

     if the stack is not empty return false
     return true
Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的.

template <typename T>   
bool parenMatching(string c) {
    stack<string> s;
    for (int i = 0; i < s.size(); i++) {
        if (c == '(' || c == '[' || c == '{' || c == '<')
            s.push(c);
        else if (c == ')' || c == ']' || c == '}' || c == '>') {
            if (s.empty()) return false;
            if (s.top() != '(' || s.top() != '[' || s.top() != '{' || s.top() != '<')
                return false;
            s.pop();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*rey 9

一个问题是堆栈的类型,它应该是

stack<char> s;
Run Code Online (Sandbox Code Playgroud)

然后for循环,条件应该是

i < c.size()
Run Code Online (Sandbox Code Playgroud)

下一个问题是

if (c == '(' || c == '[' || c == '{' || c == '<')
Run Code Online (Sandbox Code Playgroud)

不比较字符串的字符ci,所以你需要

const char c2 = c[i];
if (c2 == '(' || c2 == '[' || c2 == '{' || c2 == '<')
Run Code Online (Sandbox Code Playgroud)

如果你需要帮助来解决剩下的问题,让我/我们知道:)