PHP练习-判断字符串内括号是否对应

2020-08-07 18:31 By "Powerless" 2641 0 1

思路分析

可以理解为res是一个堆。

有左括号时将左括号入堆,有右括号时弹出最后入堆的括号判断是否匹配。

function check($str)
{
    $res = [];
    for ($i=0;$i<strlen($str);$i++){
        $v = $str[$i];
        if($v == '(' || $v == '[' || $v == '{'){
            array_push($res,$v);
        }
        if($v == ')' && array_pop($res) != '('){
            return '匹配错误';
        }
        if($v == ']' && array_pop($res) != '['){
            return '匹配错误';
        }
        if($v == '}' && array_pop($res) != '{'){
            return '匹配错误';
        }
    }
}
$str = '{[([{}])]}';
echo check($str);


评 论

View in WeChat

Others Discussion

  • 分布式服务限流
    Posted on 2020-02-07 18:57
  • 有状态服务VS无状态服务
    Posted on 2020-02-07 18:18
  • 企业级PAAS云平台几个关键问题和挑战
    Posted on 2019-06-12 18:33
  • MySQL 单库后期分库策略
    Posted on 2019-08-19 14:31
  • 关于HTTPS的五大误区
    Posted on 2020-02-02 01:10
  • Redis七大经典问题
    Posted on 2021-05-27 11:14
  • PHP扩展GD安装
    Posted on 2018-10-29 18:29
  • PHP实现精确发布时间
    Posted on 2018-12-06 21:00

1.282596s