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

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

  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • PHP练习-移动数组内的0到最后并保持其他元素顺序不变
    Posted on 2020-08-14 20:32
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20