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

2020-08-07 18:31 By "Powerless" 2769 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

  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00