《算法》第四版 答案(一)習(xí)題1.3及環(huán)境配置

在大二快過完兩個(gè)月的時(shí)候我終于開始想刻苦學(xué)習(xí)了胞得。。稼跳。(尷尬啊~)
所以希望在這剩下的兩個(gè)月的時(shí)候能夠刷完《算法》第四版盟庞,然后把題海刷完作為新年禮物送給自己。求圍觀岂贩,好讓我堅(jiān)持下去C>!萎津!哈哈哈~

這些答案有我自己寫的卸伞,也有官網(wǎng)上的,也有參照網(wǎng)上別人的答案锉屈,所以
如果有錯(cuò)誤或者是更好的解法或者是代碼風(fēng)格荤傲,歡迎指出,歡迎一起學(xué)習(xí)颈渊。

先貼出官網(wǎng)地址:http://algs4.cs.princeton.edu
(學(xué)習(xí)的時(shí)候多上官網(wǎng)多查官網(wǎng)文檔是一個(gè)很好的習(xí)慣哦~
附:官網(wǎng)上也有習(xí)題答案)

在CSDN上發(fā)現(xiàn)一個(gè)良心博主遂黍,習(xí)題答案很不錯(cuò)终佛,
貼出網(wǎng)址,歡迎大家去學(xué)習(xí)~
http://blog.csdn.net/furzoom/article/details/52692580

環(huán)境包下載

官網(wǎng)教程:http://algs4.cs.princeton.edu/windows/

由于《算法》中StdIn/StdOut 是作者自己寫的庫(kù)雾家,Java中是沒有這些庫(kù)的铃彰,所以要運(yùn)行書中的代碼的話就要在網(wǎng)上下載這些庫(kù)的實(shí)現(xiàn)。

實(shí)現(xiàn)方法:在官網(wǎng)下載algs4.jar和stdlib.jar兩個(gè)包芯咧,將其導(dǎo)入eclipse中即可牙捉。下載地址如下:
http://algs4.cs.princeton.edu/code/algs4.jar
http://introcs.cs.princeton.edu/java/stdlib/stdlib.jar

導(dǎo)入步驟的圖片如下:


image.png

第一章 1.3 背包,隊(duì)列和棧

  • 1.3.1
    答案
  public boolean isFull()          
   {  return N == a.length;   }

整個(gè)程序


import java.util.Iterator;
import java.util.NoSuchElementException;

public class FixedCapacityStackOfStrings implements Iterable<String> {
    private String[] a;  // holds the items
    private int N;       // number of items in stack

    // create an empty stack with given capacity
    public FixedCapacityStackOfStrings(int capacity) {
        a = new String[capacity];
        N = 0;
    }

    public boolean isEmpty()            {  return N == 0;                    }
    public boolean isFull()             {  return N == a.length;             }
    public void push(String item)       {  a[N++] = item;                    }
    public String pop()                 {  return a[--N];                    }
    public String peek()                {  return a[N-1];                    }
    public Iterator<String> iterator()  { return new ReverseArrayIterator(); }


    public class ReverseArrayIterator implements Iterator<String> {
        private int i = N-1;

        public boolean hasNext() {
            return i >= 0;
        }

        public String next() { 
            if (!hasNext()) throw new NoSuchElementException();
            return a[i--];
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }


    public static void main(String[] args) {
        int max = Integer.parseInt(args[0]);
        FixedCapacityStackOfStrings stack = new FixedCapacityStackOfStrings(max);
        while (!StdIn.isEmpty()) {
            String item = StdIn.readString();
            if (!item.equals("-")) stack.push(item); 
            else if (stack.isEmpty())  StdOut.println("BAD INPUT"); 
            else                       StdOut.print(stack.pop() + " ");
        }
        StdOut.println();

        // print what's left on the stack
        StdOut.print("Left on stack: ");
        for (String s : stack) {
            StdOut.print(s + " ");
        }
        StdOut.println();
    } 
} 
  • 1.3.2
    答案
was best times of the was the it (1 left on stack)
  • 1.3.3
    答案
b f g
  • 1.3.4
    官網(wǎng)答案
/******************************************************************************
 *  Compilation:  javac Parentheses.java
 *  Execution:    java Parentheses
 *  Dependencies: In.java Stack.java
 *
 *  Reads in a text file and checks to see if the parentheses are balanced.
 *
 *  %  java Parentheses
 *  [()]{}{[()()]()}
 *  true
 *
 *  % java Parentheses
 *  [(]) 
 *  false
 *
 ******************************************************************************/

public class Parentheses {
    private static final char LEFT_PAREN     = '(';
    private static final char RIGHT_PAREN    = ')';
    private static final char LEFT_BRACE     = '{';
    private static final char RIGHT_BRACE    = '}';
    private static final char LEFT_BRACKET   = '[';
    private static final char RIGHT_BRACKET  = ']';

    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == LEFT_PAREN)   stack.push(LEFT_PAREN);
            if (s.charAt(i) == LEFT_BRACE)   stack.push(LEFT_BRACE);
            if (s.charAt(i) == LEFT_BRACKET) stack.push(LEFT_BRACKET);

            if (s.charAt(i) == RIGHT_PAREN) {
                if (stack.isEmpty())           return false;
                if (stack.pop() != LEFT_PAREN) return false;
            }

            else if (s.charAt(i) == RIGHT_BRACE) {
                if (stack.isEmpty())           return false;
                if (stack.pop() != LEFT_BRACE) return false;
            }

            else if (s.charAt(i) == RIGHT_BRACKET) {
                if (stack.isEmpty())             return false;
                if (stack.pop() != LEFT_BRACKET) return false;
            }
        }
        return stack.isEmpty();
    }


    public static void main(String[] args) {
        In in = new In();
        String s = in.readAll().trim();
        StdOut.println(isBalanced(s));
    }
}


  • 1.3.5
    答案
打印 N 的二進(jìn)制表示 (當(dāng)n為50時(shí)為110010)敬飒。
  • 1.3.6
    答案
反轉(zhuǎn)隊(duì)列上的項(xiàng)目
  • 1.3.7
    官網(wǎng)答案
/******************************************************************************
 *  Compilation:  javac Stack.java
 *  Execution:    java Stack < input.txt
 *  Dependencies: StdIn.java StdOut.java
 *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt
 *
 *  A generic stack, implemented using a singly linked list.
 *  Each stack element is of type Item.
 *
 *  This version uses a static nested class Node (to save 8 bytes per
 *  Node), whereas the version in the textbook uses a non-static nested
 *  class (for simplicity).
 *  
 *  % more tobe.txt 
 *  to be or not to - be - - that - - - is
 *
 *  % java Stack < tobe.txt
 *  to be not that or be (2 left on stack)
 *
 ******************************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Stack<Item> implements Iterable<Item> {
    private Node<Item> first;     // top of stack
    private int n;                // size of the stack

    // helper linked list class
    private static class Node<Item> {
        private Item item;
        private Node<Item> next;
    }

    /**
     * Initializes an empty stack.
     */
    public Stack() {
        first = null;
        n = 0;
    }

    /**
     * Returns true if this stack is empty.
     *
     * @return true if this stack is empty; false otherwise
     */
    public boolean isEmpty() {
        return first == null;
    }

    /**
     * Returns the number of items in this stack.
     *
     * @return the number of items in this stack
     */
    public int size() {
        return n;
    }

    /**
     * Adds the item to this stack.
     *
     * @param  item the item to add
     */
    public void push(Item item) {
        Node<Item> oldfirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldfirst;
        n++;
    }

    /**
     * Removes and returns the item most recently added to this stack.
     *
     * @return the item most recently added
     * @throws NoSuchElementException if this stack is empty
     */
    public Item pop() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        Item item = first.item;        // save item to return
        first = first.next;            // delete first node
        n--;
        return item;                   // return the saved item
    }


    /**
     * Returns (but does not remove) the item most recently added to this stack.
     *
     * @return the item most recently added to this stack
     * @throws NoSuchElementException if this stack is empty
     */
    public Item peek() {
        if (isEmpty()) throw new NoSuchElementException("Stack underflow");
        return first.item;
    }

    /**
     * Returns a string representation of this stack.
     *
     * @return the sequence of items in this stack in LIFO order, separated by spaces
     */
    public String toString() {
        StringBuilder s = new StringBuilder();
        for (Item item : this) {
            s.append(item);
            s.append(' ');
        }
        return s.toString();
    }
       

    /**
     * Returns an iterator to this stack that iterates through the items in LIFO order.
     *
     * @return an iterator to this stack that iterates through the items in LIFO order
     */
    public Iterator<Item> iterator() {
        return new ListIterator<Item>(first);
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator<Item> implements Iterator<Item> {
        private Node<Item> current;

        public ListIterator(Node<Item> first) {
            current = first;
        }

        public boolean hasNext() {
            return current != null;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next; 
            return item;
        }
    }


    /**
     * Unit tests the {@code Stack} data type.
     *
     * @param args the command-line arguments
     */
    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)");
    }
}


  • 1.3.8
沒有在書中找到DoublingStackOfStrings的代碼
歡迎大家指出
  • 1.3.9
    答案
 public static String getCompleteExpression(String exp)  
    {  
        String[] params = exp.split(" ");  
        Stack<String> oprStack = new Stack<String>();  
        Stack<String> dataStack = new Stack<String>();  
        for (int i = 0; i < params.length; i++) {  
            if (isOperator(params[i])) {  
                oprStack.push(params[i]);  
            } else if (params[i].equals(")")) {  
                String d1 = dataStack.pop();  
                String d2 = dataStack.pop();  
                String op = oprStack.pop();  
                dataStack.push("( " + d2 + " " + op + " "+ d1 + " )");  
            } else {  
                dataStack.push(params[i]);  
            }  
        }  
        return dataStack.pop();  
    }  
     
    public static void main(String[] args)  
    {  
        String expression = "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )";  
        String result = getCompleteExpression(expression);  
        System.out.println(result);  
    }  
      
    private static boolean isOperator(String s)  
    {  
        return (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/"));  
    }  
   
  • 1.3.10
    答案
/******************************************************************************
 *  Compilation:  javac InfixToPostfix.java
 *  Execution:    java InfixToPostFix
 *  Dependencies: Stack.java StdIn.java StdOut.java
 *
 *  Reads in an infix expression and outputs an equivalent postfix
 *  expression.
 *
 *  Windows users: replace [Ctrl-d] with [Ctrl-z] to signify end of file.
 * 
 *  % java InfixToPostfix
 *  ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )
 *  [Ctrl-d]
 *  2 3 4 + 5 6 * * + 
 *
 *  % java InfixToPostfix | java EvaluatePostfix
 *  ( 2 + ( ( 3 + 4 ) * ( 5 * 6 ) ) )
 *  [Ctrl-d]
 *  212
 *
 ******************************************************************************/

public class InfixToPostfix {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        while (!StdIn.isEmpty()) {
            String s = StdIn.readString();
            if      (s.equals("+")) stack.push(s);
            else if (s.equals("*")) stack.push(s);
            else if (s.equals(")")) StdOut.print(stack.pop() + " ");
            else if (s.equals("(")) StdOut.print("");
            else                    StdOut.print(s + " ");
        }
        StdOut.println();
    }
}

今天時(shí)間比較倉(cāng)促邪铲,先pull下來,等明天的時(shí)候先擴(kuò)充答案然后繼續(xù)發(fā)(搬運(yùn))下面題的答案无拗。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末带到,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子英染,更是在濱河造成了極大的恐慌揽惹,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件税迷,死亡現(xiàn)場(chǎng)離奇詭異永丝,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)箭养,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門慕嚷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人毕泌,你說我怎么就攤上這事喝检。” “怎么了撼泛?”我有些...
    開封第一講書人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵挠说,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我愿题,道長(zhǎng)损俭,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任潘酗,我火速辦了婚禮杆兵,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘仔夺。我一直安慰自己琐脏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著日裙,像睡著了一般吹艇。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上昂拂,一...
    開封第一講書人閱讀 52,262評(píng)論 1 308
  • 那天受神,我揣著相機(jī)與錄音,去河邊找鬼格侯。 笑死路克,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的养交。 我是一名探鬼主播,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼瓢宦,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼碎连!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起驮履,我...
    開封第一講書人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤鱼辙,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后玫镐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體倒戏,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年恐似,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了杜跷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡矫夷,死狀恐怖葛闷,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情双藕,我是刑警寧澤淑趾,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站忧陪,受9級(jí)特大地震影響扣泊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜嘶摊,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一延蟹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧更卒,春花似錦等孵、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)果录。三九已至,卻和暖如春咐熙,著一層夾襖步出監(jiān)牢的瞬間弱恒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工棋恼, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留返弹,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓爪飘,卻偏偏與公主長(zhǎng)得像义起,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子师崎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,283評(píng)論 25 707
  • 相愛十年默终,我們有一個(gè)可愛聰慧的孩子,如今過著想要的生活犁罩,幸福滿滿齐蔽。 12月,當(dāng)北方霧霾嚴(yán)重床估、天寒地凍的時(shí)候含滴,云南大...
    鯨魚家檸檸閱讀 339評(píng)論 2 4
  • 喜歡紫玉蘭。春天丐巫,她一樹繁花谈况,夏天,她綠蔭滿院递胧。 紫紅色花朵,幽姿淑態(tài),別具風(fēng)情
    阿拉蕾唷閱讀 343評(píng)論 2 4