基礎(chǔ)篇(5)LeetCode--CHAPTER 4. STACK AND QUEUE

Unit 1 Practice I

LeetCode 225. Implement Stack using Queues
Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.

Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Click to see the details of three solutions.

public class MyStack {
            
   private Queue<Integer> queue = new LinkedList<>();
        
    /** Initialize your data structure here. */
    public MyStack() {
        
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.add(x);
        for (int i=1; i<queue.size(); i++)
            queue.add(queue.remove());
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.remove();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
       return queue.isEmpty();
    }
}

Unit 2 Practice II

LeetCode 20. Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

挨個(gè)檢查給的String里的每個(gè)character,如果是左括號(hào)命浴,相應(yīng)的右括號(hào)入棧齐邦;如果是右括號(hào)讥蔽,先檢查棧拧略,如果為空绷杜,證明不能匹配岛蚤,如果棧不空酝锅,彈出棧頂元素top,檢查是否與當(dāng)前的右括號(hào)匹配蒿赢,不匹配返回false润樱。當(dāng)字符全都檢查完后,判斷棧是否為空羡棵,空則說明都匹配壹若,不空則證明有沒匹配的。

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<Character>();
    for (char c: s.toCharArray()) {
        if (c == '(') {
            stack.push(')');
        }
        else if (c == '[') {
            stack.push(']');
        }
        else if (c == '{') {
            stack.push('}');
        }
        else if (stack.isEmpty() || stack.pop() != c) {
            return false;
        }
    }
    return stack.isEmpty();
}               

Unit 3 Practice III

LeetCode 232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.

Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.

Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

public class MyQueue {
    Stack<Integer> queue = new Stack<Integer>();
    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        Stack<Integer> temp = new Stack<Integer>();
        while(!queue.empty()){
            temp.push(queue.pop());
        }
        queue.push(x);
        while(!temp.empty()){
            queue.push(temp.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return queue.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return queue.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return queue.empty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

Unit 4 Practice IV

LeetCode 102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

BTLOT.jpg
public List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> result = new ArrayList<>();
    if (root == null) {
        return result;
    }
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.offer(root);
    int curDeep = 0;
    while(!queue.isEmpty()) {
        curDeep = queue.size();
        List<Integer> levelResult = new ArrayList<>();
        for (int i = 0; i < curDeep; i++) {
            TreeNode peek = queue.poll();
            levelResult.add(peek.val);
            if(peek.left != null) {
                queue.offer(peek.left);
            }
            if(peek.right!=null) {
                queue.offer(peek.right);
            }
        }
        result.add(levelResult);
    }
    return result;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末皂冰,一起剝皮案震驚了整個(gè)濱河市店展,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌秃流,老刑警劉巖赂蕴,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異舶胀,居然都是意外死亡概说,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門嚣伐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來糖赔,“玉大人,你說我怎么就攤上這事轩端》诺洌” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)奋构。 經(jīng)常有香客問我骨田,道長(zhǎng),這世上最難降的妖魔是什么声怔? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮舱呻,結(jié)果婚禮上醋火,老公的妹妹穿的比我還像新娘。我一直安慰自己箱吕,他們只是感情好芥驳,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著茬高,像睡著了一般兆旬。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上怎栽,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天丽猬,我揣著相機(jī)與錄音,去河邊找鬼熏瞄。 笑死脚祟,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的强饮。 我是一名探鬼主播由桌,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼邮丰!你這毒婦竟也來了行您?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤剪廉,失蹤者是張志新(化名)和其女友劉穎娃循,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體斗蒋,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡淮野,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了吹泡。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片骤星。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖爆哑,靈堂內(nèi)的尸體忽然破棺而出洞难,到底是詐尸還是另有隱情,我是刑警寧澤揭朝,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布队贱,位于F島的核電站色冀,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏柱嫌。R本人自食惡果不足惜锋恬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望编丘。 院中可真熱鬧与学,春花似錦、人聲如沸嘉抓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽抑片。三九已至卵佛,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間敞斋,已是汗流浹背截汪。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留植捎,地道東北人挫鸽。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像鸥跟,于是被迫代替她去往敵國(guó)和親丢郊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

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