數據結構-PHP 實現 '棧' 結構匹配花括號有效性

這篇文章是展現如何使用棧(Stack)這種數據結構來匹配花括號有效性,首先拋出問題,這裏直接貼出問題以下:php

給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
-------------------------------------------------
示例 1:
輸入: "()"
輸出: true
示例 2:

輸入: "()[]{}"
輸出: true
示例 3:

輸入: "(]"
輸出: false
示例 4:

輸入: "([)]"
輸出: false
示例 5:

輸入: "{[]}"
輸出: true

1.output_match_bracket.php

這是一個調用和打印輸出結果的展現文件:git

<?php
require 'MatchBracket.php';
$matchBracket = new MatchBracket();
$str = "[()[{[]}]{}]({([]([()][]))})";
var_dump($matchBracket->isValid($str)); //輸出true
$str = "[()[{[]}]{}]({([]([()][}]))})";
var_dump($matchBracket->isValid($str)); //輸出false

2.MatchBracket 類

這個類主要做用是接收須要匹配的字符串,而後調用 入棧出棧 邏輯,經過巧妙的抵消花括號的方法來判斷花括號是否封閉:segmentfault

<?php
require 'StackStruct.php';
/**
 * 匹配花括號
 * Class MatchBracket
 */class MatchBracket
{
 /**
 * 判斷花括號是否有效封閉
 * @param string $str
 * @return bool
 */ public function isValid(string $str): bool
 {
 $stackStruct = new StackStruct();
 //若字符串長度爲奇數,則確定不封閉
 if (strlen($str) % 2 == 1) {
 return false;
 }
 //先將花括號字符串依次入棧,若遇到 ] ) },需查看棧頂是否對應是 [ ( { for ($i = 0; $i < strlen($str); $i++) {
 if (!$stackStruct->isEmpty() && $str[$i] == "]" && $stackStruct->peek() != "[") {
 return false;
 } elseif (!$stackStruct->isEmpty() && $str[$i] == ")" && $stackStruct->peek() != "(") {
 return false;
 } elseif (!$stackStruct->isEmpty() && $str[$i] == "}" && $stackStruct->peek() != "{") {
 return false;
 } elseif (!$stackStruct->isEmpty() && $str[$i] == "]" && $stackStruct->peek() == "[") {
 $stackStruct->pop(); //出棧抵消
 } elseif (!$stackStruct->isEmpty() && $str[$i] == ")" && $stackStruct->peek() == "(") {
 $stackStruct->pop(); //出棧抵消
 } elseif (!$stackStruct->isEmpty() && $str[$i] == "}" && $stackStruct->peek() == "{") {
 $stackStruct->pop(); //出棧抵消
 } else {
 $stackStruct->push($str[$i]);
 }
 } //如 "$str=[({" ,最後棧不爲空,則表示括號不封閉
 if (!$stackStruct->isEmpty()) {
 return false;
 }
 return true;
 }
}

3.StackStruct 棧類

這裏是一個 類,它的繼承了數組類的方法,經過數組的增刪查封裝的一個 類,實現了 入棧(push)出棧(pop)查看棧頂(peek)數組

<?php
require 'ArrayStruct.php';
require 'Stack.php';
/**
 * 數組實現棧
 * Class StackStruct
 */class StackStruct implements Stack
{
 //數組類對象,用於存放棧元素
 public $array = null;
 /**
 * 構造函數 定義棧的容量
 * ArrayStruct constructor.
 * @param int $capacity
 */
 public function __construct(int $capacity = 10)
 { $this->array = new ArrayStruct($capacity);
 }
 /**
 * 獲取棧大小
 * @return int
 */ public function getSize(): int
 {
 return $this->array->getSize();
 }
 /**
 * 判斷棧是否爲空
 * @return bool
 */ public function isEmpty(): bool
 {
 return $this->array->isEmpty();
 }
 /**
 * 元素入棧
 */
 public function push($e): void
 {
 $this->array->addLast($e);
 }
 /**
 * 出棧
 * @return mixed
 */ public function pop()
 { return $this->array->removeLast();
 }
 /**
 * 查看棧頂元素
 * @return mixed
 */ public function peek()
 { return $this->array->getLast();
 }
 /**
 * 將棧數組轉化爲字符串
 * @return string
 */ public function toString(): string
 {
 return $this->array->toString();
 }
}

4.interface Stack

這裏是 類一個實現接口,裏面定義了一些函數,這樣 StackStrcut 繼承它以後,必須重構裏面的全部方法:數據結構

<?php
interface Stack
{
 /**
 * 獲取棧大小
 * @return int
 */ public function getSize(): int;
 /**
 * 判斷棧是否爲空
 * @return bool
 */ public function isEmpty(): bool;
 /**
 * 元素入棧
 */
 public function push($e): void;
 /**
 * 出棧
 * @return mixed
 */ public function pop();
 /**
 * 查看棧頂元素
 * @return mixed
 */ public function peek();
}

5.ArrayStruct 數組類

這是封裝好的一個數組類,能實現數組的基本功能:函數

<?php
/**
 * 數據結構-數組的實現
 * Class ArrayStruct
 */class ArrayStruct
{
 //用於存放數據
 protected $data = [];
 //用於標記數組大小
 protected $size = 0;
 //用於標記數組的容量
 protected $capacity = 10;
 /**
 * 構造函數 定義數組容量
 * ArrayStruct constructor.
 * @param int $capacity
 */
 public function __construct(int $capacity = 10)
 { $this->capacity = $capacity;
 }
 /**
 * 獲取數組元素個數
 * @return int
 */ public function getSize(): int
 {
 return $this->size;
 }
 /**
 * 獲取數組的容量
 * @return int
 */ public function getCapacity(): int
 {
 return $this->capacity;
 }
 /**
 * 判斷數組是否爲空
 * @return bool
 */ public function isEmpty(): bool
 {
 return $this->size == 0;
 }
 /**
 * 向數組指定位置插入元素
 * @param int $index
 * @param $e
 * @throws Exception
 */ public function add(int $index, $e): void
 {
 if ($this->size == $this->capacity) {
 $this->resize(2); //擴大到原來的2倍
 }
 if ($index < 0 || $index > $this->size) {
 echo "添加位置超出數組大小";
 exit; }
 //爲了方便理解,[1,2,4,5,6],假設 $index = 3; $e = 100,插入以後[1,2,4,100,5,6]
 for ($i = $this->size; $i >= $index; $i--) {
 $this->data[$i] = $this->data[$i - 1];
 }
 $this->data[$index] = $e;
 $this->size++;
 }
 /**
 * 向數組末尾添加元素
 * @param $e
 * @throws Exception
 */ public function addLast($e): void
 {
 $this->add($this->size, $e);
 }
 /**
 * 向數組開頭插入元素
 * @param $e
 * @throws Exception
 */ public function addFirst($e): void
 {
 $this->add(0, $e);
 }
 /**
 * 獲取 index 位置數組元素
 * @param int $index
 * @return mixed
 */ public function get(int $index)
 { if ($index < 0 || $index > $this->size) {
 echo "index值超出元素的位置範圍,";
 exit; }
 return $this->data[$index];
 }
 /**
 * 獲取數組末尾元素
 * @return mixed
 */ public function getLast()
 { return $this->get($this->size - 1);
 }
 /**
 * 判斷數組中是否存在某個元素
 * @param $e
 * @return bool
 */ public function contains($e): bool
 {
 for ($i = 1; $i < $this->size; $i++) {
 if ($this->data[$i] == $e) {
 return true;
 }
 }
 return false;
 }
 /**
 * 查某個元素在數組的位置索引值,若不存在則返回 -1
 * @param $e
 * @return int
 */ public function find($e): int
 {
 for ($i = 0; $i < $this->size; $i++) {
 if ($this->data[$i] == $e) {
 return $i;
 }
 }
 return -1;
 }
 /**
 * 刪除數組指定位置元素,返回刪除元素的值
 * @param $index
 * @return mixed
 */ public function remove($index)
 { if ($index < 0 || $index > $this->size) {
 echo "index值超出元素的位置範圍,";
 exit; }
 $e = $this->data[$index];
 for ($i = $index; $i < $this->size - 1; $i++) {
 $this->data[$i] = $this->data[$i + 1];
 }
 $this->size--;
 $this->data[$this->size] = null; //loitering objects ! =memory
 /** 若當前數組大小,小於容量的一半,則從新分配一半的數組空間大小 **/
 if ($this->size <= $this->capacity / 4 && $this->capacity % 2 == 0) {
 $this->resize(0.5);
 }
 return $e;
 }
 /**
 * 刪除數組首個元素,返回刪除元素的值
 */
 public function removeFirst()
 { return $this->remove(0);
 }
 /**
 * 刪除數組首個元素,返回刪除元素的值
 */
 public function removeLast()
 { return $this->remove($this->size - 1);
 }
 /**
 * 刪除數組中特定元素
 * @param $e
 */
 public function removeElement($e)
 { for ($i = 0; $i < $this->size; $i++) {
 if ($this->data[$i] == $e) {
 $this->remove($i);
 $this->removeElement($e);
 break; }
 } }
 /**
 * 數組擴容,如果其餘語言,如JAVA這裏須要從新開闢空間
 * @param $factor
 */
 protected function resize($factor)
 { $this->capacity = $factor * $this->capacity;
 }
 /**
 * 將數組轉化爲字符串
 * @return string
 */ public function toString(): string
 {
 $str = "[";
 for ($i = 0; $i < $this->size; $i++) {
 $value_str = is_numeric($this->data[$i]) ? $this->data[$i] : "'{$this->data[$i]}'";
 $str .= $i . " => " . $value_str . ",";
 }
 $str = trim($str, ",");
 $str .= "]";
 return $str;
 }
}
Tips:若對 不熟悉,能夠參考以前文章 數據結構-PHP經過 Array 類對象實現 "棧"數據結構-PHP實現Array

代碼倉庫 :https://gitee.com/love-for-po...ui

掃碼關注愛因詩賢
this

相關文章
相關標籤/搜索