//给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
//
// 有效字符串需满足:
//
//
// 左括号必须用相同类型的右括号闭合。
// 左括号必须以正确的顺序闭合。
//
//
// 注意空字符串可被认为是有效字符串。
//
// 示例 1:
//
// 输入: "()"
//输出: true
//
//
// 示例 2:
//
// 输入: "()[]{}"
//输出: true
//
//
// 示例 3:
//
// 输入: "(]"
//输出: false
//
//
// 示例 4:
//
// 输入: "([)]"
//输出: false
//
//
// 示例 5:
//
// 输入: "{[]}"
//输出: true
// Related Topics 栈 字符串
难道系数:简单
这题是数据结构栈的应用,两种解法如下:
01
<?php
//括号判断
class Parentheses
{
private $stack = [];
private $top = -1;
public function Vilid($s)
{
$arr = [
')' => '(',
']' => '[',
'}' => '{'
];
$len = strlen($s);
//括号成对出现,奇数个先排除
if ($len % 2 !== 0) {
echo "奇数个先排除";
return false;
}
//s 中出现arr的key则弹出,其余入栈
for ($i = 0; $i < $len; $i++) {
//$s[$i] => key arr[$s[$i]] => value
if (isset($arr[$s[$i]])) {
//栈顶元素为对应value,则出栈
if ($this->stack[$this->top] == $arr[$s[$i]]) {
//出栈 栈顶值-1
array_pop($this->stack);
--$this->top;
} else {
echo "错误";
return false;
}
} else {
//入栈 栈顶值+1
array_push($this->stack, $s[$i]);
++$this->top;
}
}
if ($this->top > -1) {
echo "失败";
return false;
} else {
echo "成功";
return true;
}
}
}
$a = new Parentheses();
$a->Vilid('[]{(())}');
02
<?php
//括号判断
class Parentheses
{
private $stack = [];
public function Vilid($s)
{
$left = ['(' => 1, '[' => 1, '{' => 1];
$len = strlen($s);
if ($len % 2 !== 0) {
echo "奇数个先排除";
return false;
}
for ($i = 0; $i < $len; $i++) {
//找到左括号,(左括号)入栈
if(isset($left[$s[$i]])){
array_push($this->stack,$s[$i]);
}else{
//第一个一定为左括号,不是则直接退出
if(empty($this->stack)) return false;
//判断当前符号与栈顶元素是否匹配,不是直接退出
if($s[$i]==')'&&array_pop($this->stack)!=='('){
echo "错误)";
return false;
}
if($s[$i]==']'&&array_pop($this->stack)!=='['){
echo '错误]';
return false;
}
if($s[$i]=='}'&&array_pop($this->stack)!=='{'){
echo "错误}";
return false;
}
}
}
//最后判断栈是否为空
if(empty($this->stack)){
echo "成功";
return true;
}else{
echo "失败";
print_r($this->stack);
return false;
}
}
}
$a = new Parentheses();
$a->Vilid('[]{()}');