11 Star 16 Fork 4

爱因诗贤/数据结构和算法

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Stack.php 2.68 KB
一键复制 编辑 原始数据 按行查看 历史
Guo-Hongfu 提交于 2020-10-21 22:44 +08:00 . 第二天学习,数据结构之栈
<?php
require '../array/ArrayList.php';
/**
* Class Stack
* 实现栈、
* 可以继承 ArrayList 类
* 接口设计
* @size() 元素的数量
* @isEmpty() 是否为空
* @push(item) 入栈
* @pop() 出栈
* @top() 获取栈顶元素
* @clear() 清空栈元素
*/
class Stack
{
private $arrayList=null;
public function __construct()
{
// 代理类
$this->arrayList = new ArrayList();
}
public function size() : int
{
return $this->arrayList->getSize();
}
public function isEmpty(){
return $this->arrayList->isEmpty();
}
public function push($item):void
{
$this->arrayList->add($item);
}
public function pop()
{
return $this->arrayList->remove($this->arrayList->getSize()-1);
}
public function top(){
return $this->arrayList->get($this->arrayList->getSize()-1);
}
public function clear():void
{
$this->arrayList->clear();
}
public function __toString():string
{
return $this->arrayList->__toString();
}
}
class Solution {
protected static $solution = [
'(' => ')',
'{' => '}',
'[' => ']'
];
/**
* 题目来源力扣
* https://leetcode-cn.com/problems/valid-parentheses/
* 判断是否是有效的括号
* @param String $s
* @return Boolean
*/
public function isValid($s) {
$stack = new Stack();
$len = strlen($s);
for($i=0;$i<$len;$i++){
$char = $s[$i];
// 第二版优化
if (in_array($char,array_keys(self::$solution))){
$stack->push($char);
}else{
if($stack->isEmpty()) return false;
$left = $stack->pop();
if($char !== self::$solution[$left]) return false;
}
// 第一版
// if('(' === $char || '{' === $char || '[' === $char){
// // 入栈。左字符进行入栈,为什么是左字符,如果第一个是右字符的话,那肯定不是有效的括号
// $stack->push($char);
// } else{
// if($stack->isEmpty()) return false;
// $left = $stack->pop();
//
// if('(' === $left && ')' !== $char)return false;
// if('{' === $left && '}' !== $char)return false;
// if('[' === $left && ']' !== $char)return false;
//
// }
}
return $stack->isEmpty();
}
}
$stack = new Stack();
$stack->push(1);
$stack->push(2);
$stack->push(3);
//var_dump($stack->size());
$solution = new Solution();
$ret = $solution->isValid('([{]}])');
var_dump($ret);
//var_dump((string)$stack);
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
PHP
1
https://gitee.com/love-for-poetry/data-structure.git
git@gitee.com:love-for-poetry/data-structure.git
love-for-poetry
data-structure
数据结构和算法
theday

搜索帮助