🫠

Leet Code [20] Valid Parentheses

2023/12/12に公開

leetcode始めます。
主にPHPを使います。
まれにJSやRubyを使うかもしれません。
ごくまれに他の言語に挑戦するかもしれません。

https://leetcode.com/problems/valid-parentheses/

<?php
/*
 * @lc app=leetcode id=20 lang=php
 *
 * [20] Valid Parentheses
 */

// @lc code=start
class Solution {

    /**
     * @param String $s
     * @return Boolean
     */
    function isValid($s) {
        if (strlen($s) % 2 !== 0) {
            return false;
        }
        $brackets = [
            '(' => [
                'start_end' => 'start',
                'pair' => ')'
            ],
            ')' => [
                'start_end' => 'end',
                'pair' => '('
            ],
            '[' => [
                'start_end' => 'start',
                'pair' => ']'
            ],
            ']' => [
                'start_end' => 'end',
                'pair' => '['
            ],
            '{' => [
                'start_end' => 'start',
                'pair' => '}',
            ],
            '}' => [
                'start_end' => 'end',
                'pair' => '{',
            ],
        ];

        $allows = [];
        $length = strlen($s);
        for ($i = 0; $i <= $length - 1; $i++) {
            $str = substr($s, $i, 1);
            if ($brackets[$str]['start_end'] === 'end' && $str !== end($allows)) {
                return false;
            }
            if ($brackets[$str]['start_end'] === 'end' && $str === end($allows)) {
                array_pop($allows);
                continue;
            }

            array_push($allows, $brackets[$str]['pair']);
        }

        if (count($allows) !== 0) {
            return false;
        }

        return true;

    }
}
// @lc code=end

Discussion