算法第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;
    }
}
发布了91 篇原创文章 · 获赞 15 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/vadonmo/article/details/78515852
1.3