一徘郭、js棧(數(shù)組方式)
class Stack{
constructor(){
this.item = [];
}
push(element) {//添加棧元素
this.item.push(element);
}
pop(){//刪除棧頂元素
return this.item.pop();
}
peek() {//返回棧頂元素
return this.item[this.item.length-1];
}
clear(){//清除棧中得所有元素
this.item = [];
}
isEmpty() {//判斷棧是否為空
return this.item.length === 0;
}
size() {//返回棧長(zhǎng)度
return this.item.length;
}
toString() {//轉(zhuǎn)化成字符串
return this.item.toString();
}
}
二、js棧(對(duì)象方式)
class Stack {
constructor() {
this.count = 0;
this.item = {};
}
push(element) {//添加棧元素
this.item[this.count] = element;
this.count++;
}
pop(){//刪除棧頂元素
if (this.isEmpty()) return undefined;
this.count--;
const result = this.item[this.count];
delete this.item[this.count];
return result;
}
peek() {//返回棧頂元素
if (this.isEmpty()) return undefined;
return this.item[this.count - 1];
}
clear(){//清除棧中得所有元素
this.count = 0;
this.item = {};
}
isEmpty() {//判斷棧是否為空
return this.count === 0;
}
size() {//返回棧長(zhǎng)度
return this.count;
}
toString() {//轉(zhuǎn)化成字符串
if (this.isEmpty()) return '';
let objString = `${this.item[0]}`;
for (var i = 1; i < this.count; i++) {
objString = `${objString},${this.item[i]}`;
}
return objString;
}
}
三浦箱、測(cè)試遭京,以上代碼可直接在瀏覽器控制臺(tái)運(yùn)行
var aaa = new Stack();
aaa.push('ss')
aaa.push('ee')
aaa.push('rr')
console.log(aaa.toString())
console.log('棧頂元素:'+aaa.peek())
console.log('棧當(dāng)前長(zhǎng)度:'+aaa.size())
aaa.pop();
console.log(aaa.toString())
aaa.clear();
console.log(aaa.toString())
四、用途
1.問(wèn)題
判斷字符串中的{}、[]、()三種括號(hào)是否匹配
2.示例
輸入:’()’ 輸出:true
輸入:’( ) [ ]{ }’ 輸出:true
輸入:’{ ]’ 輸出:false
輸入:’( [ ) ]’ 輸出:false
輸入:’’{ [ ] }’ 輸出:true
3.思路
(1).遍歷字符串的每一個(gè)字符
(2).如果是左括號(hào)直接push入棧
(3).如果是右括號(hào),將棧頂?shù)牡谝粋€(gè)元素取出來(lái)與當(dāng)前的元素進(jìn)行對(duì)比鹅很,如果不匹配,則return false罪帖,如果匹配促煮,則出棧
(4).遍歷完之后,棧為空則該字符串的括號(hào)匹配return true整袁;否則不匹配return false