JavaScript資料結構與演算法-棧練習

來源:互聯網
上載者:User

標籤:清空   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資料結構與演算法-棧練習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.