Checking string has balanced parentheses

后端 未结 18 2404
谎友^
谎友^ 2020-12-01 08:42

I am reading the Algorithm Design Manual Second Edition and this is from an exercise question. Quoting the question

A common problem for comp

18条回答
  •  忘掉有多难
    2020-12-01 09:03

    int i;
    int len; 
    char popped;
    stack st;
    string a = "({<<";
    len = a.length();
    
    for(i=0;i' || a[i] == ')' || a[i] == ']' || a[i] == '}')
        {
            if(st.empty())
            {
                cout << "stack is empty, when popped , not balanced" << endl;
                return 0;
            }
            else
            {
                popped = st.top(); 
                st.pop();
                if (!((a[i] == '>' && popped == '<') || (a[i] == ')' && popped == '(') || (a[i] == '}' && popped == '{') || (a[i] == '>' && popped == '<'))) //ok
                {
                    cout << "not balanced on character" + std::string(1,a[i]) << endl;
                    return 0;
                }
            }
    
        }
    
    }
    if(st.empty())
    {
        cout << "balanced" << endl;
    }
    else
    {
        cout << "not balanced stack not empty" << endl;
    }
    

提交回复
热议问题