题解 | 括号配对问题

括号配对问题

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

有两个需要注意的点:

1.(sta.empty()||sta.top() != '[' )这个判断是从左到右的短路判断,应该先判空,不空再判断是否匹配,否则sta.top()可能导致程序异常

2.循环结束后,栈为空才匹配完成

#include<stdio.h>
#include<stack>
#include<string>
#include <iostream>
using namespace std;

int main() {
    string str;
    getline(cin, str);
    stack<char> sta;
    for (int i = 0; i < str.size(); i++) {
        if (str[i] == '[' || str[i] == '(') {
            //进栈
            sta.push(str[i]);
        }
        else if (str[i] == ']') {
            if (sta.empty()||sta.top() != '[' ) {
                printf("false\n");
                return 0;
            }
            //匹配出栈
            sta.pop();
        }
        else if (str[i] == ')') {
            if (sta.empty()||sta.top() != '(') {
                printf("false\n");
                return 0;
            }
            //匹配出栈
            sta.pop();
        }
    }
    if (sta.empty()) {
        printf("true\n");
    }
    else {
        printf("false\n");
    }
        return 0;
}

计算机复试机试(王道版) 文章被收录于专栏

收录王道2026年计算机复试机试的(课程)代码题解,仅供个人学习参考

全部评论

相关推荐

Edgestr:没项目地址就干脆把那一栏删了呗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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