Coder Pat之路 问题 B: Problem E

本文介绍了一个用于判断给定表达式中括号是否正确匹配的程序。该程序使用栈来跟踪括号,并通过映射表确保每种类型的括号正确闭合。提供了详细的实现代码及样例输入输出。

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

问题 B: Problem E

时间限制: 1 Sec  内存限制: 32 MB

题目描述

请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。

输入

有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。

输出

对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。

样例输入

4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9

样例输出

yes
no
no
no

User: 吴锦诚
Date: 2018/7/10

#include <iostream>
#include <string>
#include <stack>
#include <map>
#include <math.h>
using namespace std;
#define MIN_VALUE 1e-8
string str;
stack<char> sta;
map<char, double> maps;
void setMaps()
{
    maps['('] = 0.1;
    maps['['] = 0.2;
    maps['{'] = 0.3;
    maps[')'] = 1.1;
    maps[']'] = 1.2;
    maps['}'] = 1.3;
}
bool equ(double a, double b)
{
    return fabs(a - b) < MIN_VALUE;
}
void func()
{
    char temp;
    int i;
    for (i = 0; i < str.length(); i++)
    {
        if (str[i] != '(' && str[i] != ')' && str[i] != '[' && str[i] != ']' && str[i] != '{' && str[i] != '}')
            continue;
        if (sta.empty())
        {
            if (maps[str[i]] > 1)
            {
                break;
            }
            else
            {
                sta.push(str[i]);
            }
        }
        else
        {
            temp = sta.top();
            if (maps[str[i]] < 1) // ([{
            {
                sta.push(str[i]);
            }
            else if (equ(maps[str[i]], maps[temp] + 1)) //  )]}
            {
                sta.pop();
            }
            else
            {
                break;
            }
        }
    }
    if (i == str.length() && sta.empty())
        cout << "yes" << endl;
    else
    {
        cout << "no" << endl;
    }
}
int main()
{
    int n;
    setMaps();
    while (cin >> n)
    {
        cin.ignore();
        for (int i = 0; i < n; i++)
        {
            getline(cin, str);
            while (!sta.empty())
                sta.pop();
            func();
        }
    }
    return 0;
}
 
/**************************************************************
    Problem: 1982
    User: morizunzhu
    Language: C++
    Result: 正确
    Time:0 ms
    Memory:2044 kb
****************************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值