PHP判断下面扩号是否闭合,左右对称即为闭合: ((())),)(()),(()))),(((((()),(()()),()()

/**
 * 检测括号是否正确, 不稳定算法(借鉴于天天向上)
 * 时间复杂度O(n)
 * @param string $checkStr
 * @return bool
 */
function checkStr(string $checkStr)
{

    $checkStr = str_replace(',', '', $checkStr);

    $strCount = strlen($checkStr);
    if ($checkStr[0] == ')' || $checkStr[$strCount - 1] == '(') {
        return false;
    }

    $count = 0;

    for ($i = 0; $i < $strCount; $i++) {
        if ($checkStr[$i] == '(') {
            $count += 1;
        } else {
            $count -= 1;
        }
    }
//    var_dump($count);
    //debug($count);
    return $count == 0;
}

/**
 * 检测括号是否完整, 不稳定算法
 * 时间复杂度O(1)
 * @param string $str
 * @return bool
 */
function checkBracket(string $str)
{
    $str_count = strlen($str);
    if ($str[0] == ')' || $str[$str_count - 1] == '(') {
        return false;
    }
    $left_bracket_num = substr_count($str, '(');
    $right_bracket_num = substr_count($str, ')');
    $diff = $left_bracket_num - $right_bracket_num;
    if ($diff != 0) return false;
    return true;
}

/**
 * 检测括号是否完整(备选), 基本稳定算法
 * 时间复杂度O(n)
 * @param string $str
 */
function checkBracket_On(string $str)
{
    $str_arr = explode(',', $str);
    $result = true;
    foreach ($str_arr as $vo) {
        $str_count = strlen($vo);
        if ($vo[0] == ')' || $vo[$str_count - 1] == '(') {
            $result = false;
        }
        $left_bracket_num = substr_count($str, '(');
        $right_bracket_num = substr_count($str, ')');
        $diff = $left_bracket_num - $right_bracket_num;
        if ($diff != 0) $result = false;
    }
    return $result;
}

你可能感兴趣的:(PHP判断下面扩号是否闭合,左右对称即为闭合: ((())),)(()),(()))),(((((()),(()()),()())