多组括号闭包问题

问题描述:判断字符串中的括号 () [] {} 是否为闭合结构。

最开始的思路是,使用堆栈的结构,遇到左括号加入堆栈头,遇到匹配的右括号则将左括号移除堆栈,最后若堆栈有剩余或过程中匹配失败,则括号结构不为闭包。

function validBraces($braces){
  $array = [];
  foreach(str_split($braces) as $item) {
    if($item == '(' || $item == '[' || $item == '{') {
      array_unshift($array,$item);
    } elseif(($array[0] == '(' && $item == ')') || ($array[0] == '[' && $item == ']') || ($array[0] == '{' && $item == '}')) {
      array_shift($array);
    } else {
      return false;
    }
  }
  return empty($array) ? true : false;
}

提交之后,虽然是勉勉强强能够完成任务,但是看了大佬们的代码后,真是感到自惭形愧。

//1、str_replace能这么智能地使用我是没想到的。。。
function validBraces($braces){
  do {
    $braces = str_replace(['()', '[]', '{}'], '', $braces, $count);
  } while ($count);
  return empty($braces);  
}
//或者
function validBraces($braces){
    $count = 1;
    while ($count) $braces = str_replace(['()', '[]', '{}'], '', $braces, $count);
    return $braces === '';
}
2、使用正则,
function validBraces($s) {
  $s = preg_replace('/[^(){}\[\]]/', "", $s);
  while (preg_match('/\(\)|\[\]|\{\}/', $s)) {
    $s = preg_replace('/\(\)|\[\]|\{\}/', "", $s);
  }
  return !$s;
}

另外,如果你有兴趣,或者是有问题想要与我探讨,欢迎来访问我的博客:https:mu-mu.cn/blog

猜你喜欢

转载自blog.csdn.net/weixin_43844995/article/details/108040465
今日推荐