🫠
Leet Code [20] Valid Parentheses
leetcode始めます。
主にPHPを使います。
まれにJSやRubyを使うかもしれません。
ごくまれに他の言語に挑戦するかもしれません。
<?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