数据结构与算法 / 编辑器和编译器如何判定括号是否合法

一、整体思路

使用这种数据结构。

遍历字符串,遇到左括号则入栈,遇到右括号则判断此时的栈顶的括号是否和右括号对应,如果是则 pop 栈顶;如果不是则直接可以判定该字符串中括号不匹配。

二、栗子

#include <stack>
#include <string>
#include <iostream>

char leftOf(char c);

bool isValid(std::string str)
{
    std::stack<char> left;
    for (char c : str)
    {
        if (c == '(' || c == '{' || c == '[')
            left.push(c);
        else // 字符 c 是右括号
            if (!left.empty() && leftOf(c) == left.top())
            left.pop();
        else
            // 和最近的左括号不匹配
            return false;
    }
    // 是否所有的左括号都被匹配了
    return left.empty();
}

char leftOf(char c)
{
    if (c == '}')
        return '{';
    if (c == ')')
        return '(';
    return '[';
}

void show(const std::string &str)
{
    if (isValid(str))
        std::cout << "合法" << std::endl;
    else
        std::cout << "不合法" << std::endl;
    return;
}

int main()
{
    show("{()}");
    show("{()[]])");
    return 0;
}
合法
不合法

 

代码参考:https://zhuanlan.zhihu.com/p/107788052

(SAW:Game Over!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值