Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’
and ‘]’, determine if the input string is valid. The brackets must
close in the correct order, “()” and “()[]{}” are all valid but “(]”
and “([)]” are not.
灵活使用栈。
代码如下:
function isValidParentheses($str) {
if (strlen($str) < 1) return false;
$arr = [];
for ($i = 0; $i < strlen($str); $i++) {
switch ($str[$i]) {
case '(': array_push($arr, ')'); break;
case '[': array_push($arr, ']'); break;
case '{': array_push($arr, '}'); break;
case ')':
case ']':
case '}':
if (empty($arr) || array_pop($arr) != $str[$i])
return false;
}
}
return empty($arr);
}
var_dump(isValidParentheses('({)[]'));