標籤:清空 for ace 個數 `` 改變 3.1 pos 元素
棧的實現
// 棧類function Stack () { this.dataStore = []; this.top = 0; // 棧頂位置 相當於length,不是索引。 this.push = push; this.pop = pop; this.peek = peek; this.clear = clear; this.length = length;}// push: 入棧function push (element) { this.dataStore[this.top++] = element;}// pop: 出棧function pop () { return this.dataStore[--this.top];}// peek: 取棧頂元素function peek () { return this.dataStore[this.top - 1];}// clear: 清空棧function clear () { this.top = 0;}// length: 棧內元素個數function length () { return this.top;}
練習一. 棧可以用來判斷一個算術運算式中的括弧是否匹配。編寫一個函數,該函數接受一個算術運算式作為參數,返回括弧缺失的位置。下面是一個括弧不匹配的算術運算式的例子:2.3 + 23 / 12 + (3.14159 * 0.24。
function findWrongBrace (express) { let s = new Stack(); for (let i = 0; i < express.length; ++i) { if (express[i] === `(`) { s.push(i); } else if (express[i] === `)`) { s.pop(); } } return `${express}的第${s.peek() + 1}個字元是不匹配的括弧。`;}// 樣本console.log(findWrongBrace(`2.3 + 23 / 12 + (3.14159 * 0.24`)); // 2.3 + 23 / 12 + (3.14159 * 0.24的第17個字元是不匹配的括弧。
二. 現實生活中棧的一個例子是佩茲糖果盒。想象一下你有一盒佩茲糖果,裡面塞滿了紅色,黃色和白色的糖果,但是你不喜歡黃色的糖果。使用棧(有可能用到多個棧)寫一段程式,在不改變盒內其他糖果疊放順序的基礎上,將黃色糖果移除。
let Candy = `rywrryywwrrryyywww`, newCandy = ``; // 類比糖果let s = new Stack();let len = Candy.length;while (len--) { if (Candy[len] !== `y`) { s.push(Candy[len]); }}while (s.length()) { newCandy += s.pop();}console.log(newCandy); // rwrrwwrrrwww
JavaScript資料結構與演算法-棧練習