forked from LeetCode-in-Php/LeetCode-in-Php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.php
32 lines (29 loc) · 985 Bytes
/
Solution.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
namespace leetcode\g0001_0100\s0020_valid_parentheses;
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #String #Stack
// #Data_Structure_I_Day_9_Stack_Queue #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
// #2023_12_07_Time_3_ms_(88.14%)_Space_19.1_MB_(76.99%)
class Solution {
/**
* @param String $s
* @return Boolean
*/
public function isValid($s) {
$stack = [];
$length = strlen($s);
for ($i = 0; $i < $length; $i++) {
$c = $s[$i];
if ($c == '(' || $c == '[' || $c == '{') {
array_push($stack, $c);
} elseif (($c == ')' && !empty($stack) && end($stack) == '(')
|| ($c == '}' && !empty($stack) && end($stack) == '{')
|| ($c == ']' && !empty($stack) && end($stack) == '[')
) {
array_pop($stack);
} else {
return false;
}
}
return empty($stack);
}
}