题目地址:https://leetcode-cn.com/problems/valid-parentheses/
思路:一个个字符循环,如果是左边的括号类型入栈, 如果是右边类型括号与栈中的最新一个元素匹配。是则出栈,否则返回错误。循环完判断栈是否为空。
class Solution {
/**
* @param String $s
* @return Boolean
*/
function isValid($s)
{
if($s=='') return true;
$s = str_split($s);
if (count($s) % 2) {
return false;
}
$compare = [
')' => '(',
']' => '[',
'}' => '{',
];
$arr = [];
for ($i = 0; $i < count($s); $i++) {
if (in_array($s[$i], $compare)) {
$arr[] = $s[$i];
} elseif (array_key_exists($s[$i], $compare)) {
if ($arr[count($arr) - 1] == $compare[$s[$i]]) {
array_pop($arr);
} else {
return false;
}
} else {
return false;
}
}
if(empty($arr)){
return true;
}else{
return false;
}
}
}