Bracket Matching(Data structure)

本文介绍了一个简单的程序设计问题——括号匹配检查。该程序通过遍历输入字符串中的括号,并利用栈来判断括号是否正确配对。文章提供了完整的C++代码实现,包括输入输出流程及核心逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Check that the bracket in the input string is matched.The brackets include {,},[,],(,).

Input

The first line is an integer , namely N,which is the number of test cases . The following N lines, each line is a string no longer than 100 characters.

Output

First line of Output is an integer, namely N. number of test cases The following N lines, each line is a string of length not exceeding 100.

It is a simple and easy program,that we can just traverse the numbers and push the left brackets into a stack,when we run into the right brackets, have a comparison with the top element in the stack.Meanwhie,if the bracket is matched to the top element,then pop the top element, otherwise, continue to traverse. After the traverse, if the stackis empty, the case is matched.

code for the question(Hope make you some help)

/*@csdn_cinderella wrote at 2016.9.21 22:29*/
nclude<iostream>
#include<string>
#include<stack>

using namespace std;

int main() {
    int n;
    cin >> n;
    while (n--) {
        string str;
        stack<char> temp;
        cin >> str;
        int size = str.length();
        for (int i = 0; i < size; i++) {
            if (str[i] == '(' || str[i] == '{' || str[i] == '[') {
                temp.push(str[i]);
            } else if (str[i] == ')') {
                if (temp.empty()) {
                    temp.push(str[i]);
                } else {
                    if (temp.top() == '(') {
                        temp.pop();
                    } else {
                        temp.push(str[i]);
                    }
                }
            } else if (str[i] == '}') {
                if (temp.empty()) {
                    temp.push(str[i]);
                } else {
                    if (temp.top() == '{') {
                        temp.pop();
                    } else {
                        temp.push(str[i]);
                    }
                }
            } else if (str[i] == ']') {
                if (temp.empty()) {
                    temp.push(str[i]);
                } else {
                    if (temp.top() == '[') {
                        temp.pop();
                    } else {
                        temp.push(str[i]);
                    }
                }
            }
        }
        if (temp.empty()) {
            cout << "Yes" << endl;
        } else {
            cout << "No" << endl;
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值