-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_parentheses.php
38 lines (32 loc) · 968 Bytes
/
valid_parentheses.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
33
34
35
36
37
38
<?php
/**
* Valid Parentheses
* link - https://leetcode.com/problems/valid-parentheses
*
* Approach:
* Iterate through each parenthesis and if it is opening parenthesis, then push it to our stack
* Else (closing parenthesis), then take top from our stack (LILO) and if stack's top is not our pair, return false
* If it is our pair - remove it from stack and continue iterating
*
* Time complexity - O(n)
* Space complexity - O(n)
*/
function isValid($s) {
$parentheses = [ "(" => ")", "[" => "]", "{" => "}", ];
$stack = [];
$length = strlen($s);
for ($i = 0; $i < $length; $i++) {
$bracket = substr($s, $i, 1);
if (isset($parentheses[$bracket])) {
$stack[] = $bracket;
} else {
$stackTop = array_pop($stack);
if ($bracket !== $parentheses[$stackTop]) {
return false;
}
}
}
return $stack === [];
}
$s = "[()]{}";
echo isValid($s);