• + 0 comments

    php solution

    function isBalanced($s) {
        // Write your code here
        $stack = [];
        $left = ["(", "{", "["];
        $right = [")", "}", "]"];
        $len = strlen($s);
        for ($i = 0; $i < $len; $i++) {
            if (0 === $i && in_array($s[$i], $right)) {
                return "NO";
            }
            if (in_array($s[$i], $left)) {
                $stack[] = $s[$i];
                continue;
            }
            switch ($s[$i]) {
                case ")":
                    if ($stack[count($stack) - 1] !== "(") {
                        return "NO";
                    }
                    break;
                case "}":
                    if ($stack[count($stack) - 1] !== "{") {
                        return "NO";
                    }
                    break;
                case "]":
                    if ($stack[count($stack) - 1] !== "[") {
                        return "NO";
                    }
                    break;
            }
            array_pop($stack);
        }
        return empty($stack) ? "YES" : "NO";
    }