算法第4版 1.3 揹包、隊列和棧

1.

package com.vadonmo.exp.chapter;

/**
 * 爲FixedCapacityStackOfStrings添加一個isFull()
 * 
 * @author vadon
 *
 */
public class Exp1_3_1 {

    public class FixedCapacityStackOfStrings {
        private String[] a;
        private int N;

        public FixedCapacityStackOfStrings(int cap) {
            a = new String[cap];
        }

        public boolean isEmpty() {
            return N == 0;
        }

        /**
         * 是否滿
         * 
         * @return
         * @return boolean
         */
        public boolean isFull() {
            return a.length > N;
        }

        public int size() {
            return N;
        }

        public void push(String item) {
            a[N++] = item;
        }

        public String pop() {
            return a[--N];
        }
    }
}

2.

package com.vadonmo.exp.chapter;

import com.vadonmo.exp.api.StdIn;
import com.vadonmo.exp.api.StdOut;
import com.vadonmo.exp.example.Stack;

/**
 * 給定一下輸入,java Stack的輸出是什麼 
 * it was - the best - of times - - - it was - the - -
 * 
 * @author vadon
 *
 */
public class Exp1_3_2 {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) {
                stack.push(item);
            } else if (!stack.isEmpty()) {
                StdOut.print(stack.pop() + " ");
            }
        }
        StdOut.println("(" + stack.size() + " left on stack)");

    }
    // was best times of the was the it (1 left on stack)
}

3.

package com.vadonmo.exp.chapter;

/**
 * 假設某個用例程序會進行過一系列入棧和出棧的混合棧操作。
 * 入棧操作會將整數0-9按順序壓入棧;出棧操作會打印出返回值。
 * 下面哪種序列是不可能產生的?
 * a. 4 3 2 1 0 9 8 7 6 5
 * b. 4 6 8 7 5 3 2 9 0 1
 * c. 2 5 6 7 4 8 9 3 1 0
 * d. 4 3 2 1 0 5 6 7 8 9
 * e. 1 2 3 4 5 6 9 8 7 0
 * f. 0 4 6 5 3 8 1 7 2 9
 * g. 1 4 7 9 8 6 5 3 0 2
 * h. 2 1 4 3 6 5 8 7 9 0
 * 
 * @author vadon
 *
 */
public class Exp1_3_3 {
    /*
     * a. 4 3 2 1 0 9 8 7 6 5 T
     * b. 4 6 8 7 5 3 2 9 0 1 F
     * c. 2 5 6 7 4 8 9 3 1 0 T
     * d. 4 3 2 1 0 5 6 7 8 9 T
     * e. 1 2 3 4 5 6 9 8 7 0 T
     * f. 0 4 6 5 3 8 1 7 2 9 F
     * g. 1 4 7 9 8 6 5 3 0 2 F
     * h. 2 1 4 3 6 5 8 7 9 0 T
     */
}

4.

package com.vadonmo.exp.chapter;

import com.vadonmo.exp.api.StdIn;
import com.vadonmo.exp.api.StdOut;
import com.vadonmo.exp.example.Stack;

/**
 * 編寫一個Stack用例Parenthess,從標準輸入中讀取一個文本流並使用棧判定其中的括號是否匹配完整。
 * 
 * @author vadon
 *
 */
public class Exp1_3_4 {

    public static void main(String[] args) {
        Parenthess();
    }

    public static void Parenthess() {
        Stack<String> stack = new Stack<String>();
        String string = StdIn.readString();
        String[] items = string.trim().split("");
        for (String item : items) {
            if (item.equals("[") || item.equals("(") || item.equals("{")) {
                stack.push(item);
            } else if (!stack.isEmpty()) {
                if (item.equals("}")) {
                    if (!stack.pop().equals("{")) {
                        StdOut.println(false);
                        return;
                    }
                } else if (item.equals("]")) {
                    if (!stack.pop().equals("[")) {
                        StdOut.println(false);
                        return;
                    }
                } else if (item.equals(")")) {
                    if (!stack.pop().equals("(")) {
                        StdOut.println(false);
                        return;
                    }
                }
            }
        }
    }
    // [()]{}{[()()]()} True
    // [(]) False
}

5.

package com.vadonmo.exp.chapter;

import com.vadonmo.exp.api.StdOut;
import com.vadonmo.exp.example.Stack;

/**
 * 當N爲50時下面這段代碼會打印什麼?從較高的抽象層次描述給定正整數N時這段代碼的行爲
 * 
 * @author vadon
 *
 */
public class Exp1_3_5 {

    public static void main(String[] args) {
        int N = 50;
        Stack<Integer> stack = new Stack<Integer>();
        while (N > 0) {
            stack.push(N % 2);
            N /= 2;
        }
        for (int d : stack)
            StdOut.print(d);
        StdOut.println();
    }
    // 110010 N的二進制
}

6.

package com.vadonmo.exp.chapter;

import com.vadonmo.exp.example.Queue;
import com.vadonmo.exp.example.Stack;

/**
 * 下面這段代碼對隊列q進行了什麼操作?
 * 
 * @author vadon
 *
 */
public class Exp1_3_6 {

    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        Queue<String> q = new Queue<String>();
        while (!q.isEmpty()) {
            stack.push(q.dequeue());
        }
        while (!stack.isEmpty()) {
            q.enqueue(stack.pop());
        }
    }
    // 首尾反序
}

7.

package com.vadonmo.exp.chapter;

/**
 * 爲Stack添加一個方法peek(),返回棧中最近添加的元素(而不彈出它)
 * 
 * @author vadon
 *
 */
public class Exp1_3_7 {

//  public Item peek() {
//      Item item = first.item;
//      return item;
//  }
}

8.

package com.vadonmo.exp.chapter;

/**
 * 給定一下輸入,給出DoublingStackOfString的數組的內容和大小 
 * it was - the best - of times - - - it was - the --
 * 
 * @author vadon
 *
 */
public class Exp1_3_8 {

    // it was - the best - of times - - - it was - the --
    // 內容:it 大小 1
    // 不知道DoublingStackOfString是個毛,暫且當作棧吧
}
it was - the best - of times - - - it was - the - -
times times
best best of of of of was was the the
was was the the the the the the the the it it it it it it
it it it it it it it it it it it it it it it it it

9.

package com.vadonmo.exp.chapter;

import com.vadonmo.exp.api.StdIn;
import com.vadonmo.exp.api.StdOut;
import com.vadonmo.exp.example.Stack;

/**
 * 編寫一段程序,從標準輸入得到一個缺少左括號的表達式並打印出補全括號以後的中序表達式 。 
 * 例如:1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) ) 
 * 你得程序應該輸出 ( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )
 * 
 * @author vadon
 *
 */
public class Exp1_3_9 {

    public static void main(String[] args) {
        StdOut.print(completeParentese());
        // 1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )
        // ( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )
    }

    /**
     * 思路爲雙棧法,不需要計算結果,只需要拼裝字符串即可。
     * 
     * @return
     * @return String
     */
    public static String completeParentese() {
        Stack<String> numStack = new Stack<String>();
        Stack<String> opStack = new Stack<String>();
        while (!StdIn.isEmpty()) {
            char c = StdIn.readChar();
            if (c == '+' || c == '-' || c == '*' || c == '/') {// 操作符
                opStack.push(String.valueOf(c));
            } else if (c >= '0' && c <= '9') {// 數字
                numStack.push(String.valueOf(c));
            } else if (c == ')') {// 右括號
                String num1 = "", num2 = "", op = "";
                if (!numStack.isEmpty()) {
                    num1 = numStack.pop();// 數字出棧
                }
                if (!opStack.isEmpty()) {
                    op = opStack.pop();// 操作符出棧
                }
                if (!numStack.isEmpty()) {
                    num2 = numStack.pop();// 數字出棧
                }
                num1 = "( " + num2 + " " + op + " " + num1 + " " + c;// 補全左括號入棧
                numStack.push(num1.replace("  ", ""));//去除多餘空格
            }
        }
        String result = "";
        while (numStack.size() > 0) {
            result = numStack.pop() + result;
        }
        return result;
    }
}
發佈了90 篇原創文章 · 獲贊 14 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章