PHPは、以下の拡散符号が閉じているか否かを判断し、左右対称に閉じている:(((((((())),(())))))),(((((())()()()()()()

1693 ワード

/**
 *         ,      (       )
 *      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;
}