题解 | 括号配对问题

括号配对问题

https://www.nowcoder.com/practice/57260c08eaa44feababd05b328b897d7

#include <ios>
#include <iostream>
#include <stack>
#include <string>
using namespace std;

stack<char> st;
int main() {
    string str;
    bool result{true};
    cin >> str;
    for(int i=0;i<str.size();i++)
    {
        if (str[i] == '(' || str[i] == '[')
        {
            st.push(str[i]);
        }
        else if(str[i] == ')')
        {
            if(st.empty())
            {
                result = false;
                break;
            }
            else 
            {
                if(st.top() == '(')
                {
                    st.pop();
                }
                else
                {
                    result = false;
                    break;
                }
            }
            
        }
        else if(str[i] == ']')
        {
            if(st.empty())
            {
                result = false;
                break;
            }
            else 
            {
                if(st.top() == '[')
                {
                    st.pop();
                }
                else
                {
                    result = false;
                    break;
                }
            }
        }
    }

    cout << boolalpha <<result;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

03-08 18:11
门头沟学院 Java
Java抽象小篮子:海投就完事了,简历没什么问题,最大问题是学历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务