<?php
$arrParams = getopt("c:");

$arrCheck = checkParams($arrParams);

if (false === $arrCheck["flag"]) {
    echoMsg($arrCheck);
    exit;
}

$strClose = $arrParams["c"];

$intI = 0;

$arrCnt = array($intI => 0);

$intIsClose = 0;//长度是否闭合 0: 闭合; 1: (过多; -1: )过多;

$intOrder = 0;//闭合括号是否有序闭合 0: 有序闭合; 1: 非有序;

do {
    if (1 === strlen($strClose)) {
        $strCur = $strClose;
    } else {
        $strCur = substr($strClose, 0, 1);
    }

    $strClose = substr($strClose, 1);

    /**
     * 最大闭合长度
     * 与判断是否闭合
     */
    if ($strCur == '(') {
        $arrCnt[$intI] = $arrCnt[$intI] + 1;
        $intIsClose++;

        $intOrder = 1;
    } elseif ($strCur == ')') {
        $intI++;
        $intIsClose--;
        $arrCnt[$intI] = 0;

        $intOrder = 0;
    }

} while (!empty($strClose));

if (0 === $intIsClose
    && 0 === $intOrder
) {
    rsort($arrCnt);
    $intMaxNum = current($arrCnt);
    $arrCheck["msg"] = "是有序闭合括号字符串," . '最大闭合括号数量为: ' . $intMaxNum;
} else {
    $arrOut["flag"] = false;
    if ($intIsClose > 0) {
        $arrCheck["msg"] = "检查字符串 \"(\" 过多";
    } elseif ($intIsClose < 0) {
        $arrCheck["msg"] = "检查字符串 \")\" 过多";
    } else {
        $arrCheck["msg"] = "可能存在 \")(\" 请检查字符串";
    }
}

echoMsg($arrCheck);


/**
 * 检查入参
 */
function checkParams($arrParams = array())
{
    $arrOut = array(
        "flag"     => false,
        "msg"    => "",
    );
    if (empty($arrParams["c"])) {
        $arrOut["msg"] = "闭合字符串不得为空";
        return $arrOut;
    }

    if (0 !== strpos($arrParams["c"], "(")) {
        $arrOut["msg"] = "非闭合括号字符串";
        return $arrOut;
    }

    if (false === strpos($arrParams["c"], ")")) {
        $arrOut["msg"] = "非闭合括号字符串2";
        return $arrOut;
    }


    $arrOut["flag"] = true;

    return $arrOut;
}

/**
 * 输出函数
 */
function echoMsg($arrCheck = array())
{
    $strPre = $arrCheck["flag"] === true? "SUCCESS": "ERR";
    echo $strPre . ": " . $arrCheck["msg"];
    echo "\n";
    exit;
}
test admin$ php close.php -c "()"
SUCCESS: 是有序闭合括号字符串,最大闭合括号数量为: 1
test root$ php close.php -c "((()))"
SUCCESS: 是有序闭合括号字符串,最大闭合括号数量为: 3
test admin$ php close.php -c "((()))"
SUCCESS: 是有序闭合括号字符串,最大闭合括号数量为: 3
test root$ php close.php -c "((()))("
SUCCESS: 检查字符串 "(" 过多
test admin$ php close.php -c "((())))"
SUCCESS: 检查字符串 ")" 过多
test root$ php close.php -c "((())))("
SUCCESS: 可能存在 ")(" 请检查字符串

 

posted on 2020-08-20 17:52  黑熊一只  阅读(274)  评论(0)    收藏  举报