括号的匹配

Description

给一个长度不大于100的字符串,问该字符串里出现的括号是否合法。

字符串只会出现三种括号,“[]”,“()”,“{}”,且形如“({[]})”为合法,形如“[(])”为不合法。

Input

单组数据。

长度不大于100的字符串,字符串中不存在空格。

Output

如果该字符串中出现的所有括号都合法,输出“Yes”,否则输出“No”。

Sample Input

(a+b)!=c

Sample Output

Yes

Hint

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

bool left(char c) //判断是否为左括号
{
    if (c == '(' || c == '{' || c == '[')
    {
        return true;
    }
    return false;
}

bool right(char c) //判断是否为右括号
{
    if (c == ')' || c == '}' || c == ']')
    {
        return true;
    }
    return false;
}

bool Whether_matche(char left, char right) //判断左右括号是否匹配
{
    if (left == '(')
    {
        return (right == ')') ? true : false;
    }
    else if (left == '{')
    {
        return (right == '}') ? true : false;
    }
    else
        return (right == ']') ? true : false;
}

int main()
{
    char stack[200]; //存入左括号的栈
    int top = 0;     //栈顶
    string s;        //字符串
    cin >> s;
    int len = s.size();
    for (int i = 0; i < len; i++)
    {
        if (left(s[i]))
        {
            stack[top++] = s[i]; //左括号入栈
        }
        else if (right(s[i]))
        {
            if (Whether_matche(stack[--top], s[i])) //左右括号开始匹配
            {
                continue; //如果匹配就继续循环
            }
            else
            {
                cout << "No"; //一旦出现不匹配的括号对就直接输出no
                return 0;
            }
        }
        else
        {
            continue;
        }
    }
    if (!top)
    {
        cout << "Yes";
        return 0;
    }
    cout << "No";
    return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char buf[110], stk[110], stp;
bool Judge()
{
    stp = -1;
    for (int i = 0; buf[i]; i++)
        switch (buf[i])
        {
        case '(':
            stk[++stp] = ')';
            break;
        case '[':
            stk[++stp] = ']';
            break;
        case '{':
            stk[++stp] = '}';
            break;
        case ')':
        case ']':
        case '}':
            if (stp == -1 || stk[stp] != buf[i])
                return false;
            else
                stp--;
            break;
        }
    return true;
}
int main()
{
    while (scanf("%s", buf) != EOF)
        printf(Judge() ? "Yes\n" : "No\n");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值