zoukankan      html  css  js  c++  java
  • leetcode栈系列155 & 232 & 349

    155. Min Stack (easy)

    问题描述:

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack.

    Example:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.

    解题思路:

    用两个栈来维护:

      一个用于存储给的数字做一个普通的栈。

      另一个用于存储当前最小值。

    代码:

    class MinStack {
    public:
        /** initialize your data structure here. */
        MinStack() {
            
        }
        
        void push(int x) {
            nums.push(x);
            if(min_stack.empty())
                min_stack.push(x);
            else{
                if(x <= min_stack.top()){
                    min_stack.push(x);
                }else{
                    min_stack.push(min_stack.top());
                }
            }
        }
        
        void pop() {
            min_stack.pop();
            nums.pop();
        }
        
        int top() {
            return nums.top();
        }
        
        int getMin() {
            return min_stack.top();
        }
    private:
        stack<int> nums;
        stack<int> min_stack;
    };
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */

    -----------------------我是下一题分割线---------------------------------------

    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 toppeek/pop from topsize, 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).

    解题思路:

    用两个栈进行顺序的颠倒,需要注意的是:进队时确认所有数字都在s1中,出队时都在s2

    代码:

    class MyQueue {
    public:
        /** Initialize your data structure here. */
        MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        void push(int x) {
            if(!s2.empty()){
                while(!s2.empty()){
                    s1.push(s2.top());
                    s2.pop();
                }
            }
            s1.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            if(!s1.empty()){
                while(!s1.empty()){
                    s2.push(s1.top());
                    s1.pop();
                }
            }
            int ret = s2.top();
            s2.pop();
            return ret;
        }
        
        /** Get the front element. */
        int peek() {
            if(!s1.empty()){
                while(!s1.empty()){
                    s2.push(s1.top());
                    s1.pop();
                }
            }
            return s2.top();
        }
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return s1.empty() && s2.empty();
        }
    private:
        stack<int> s1; 
        stack<int> s2;
    };
    
    /**
     * 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();
     * bool param_4 = obj.empty();
     */

    --------------------------------我是下一题分割线------------------------------------------

    394. Decode String(medium)

    问题描述:

    Given an encoded string, return it's decoded string.

    The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

    You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

    Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

    Examples:

    s = "3[a]2[bc]", return "aaabcbc".
    s = "3[a2[c]]", return "accaccacc".
    s = "2[abc]3[cd]ef", return "abcabccdcdcdef".

    解题思路:

    用两个stack来分别存储数字和字符串。

    并对当前可能出现的字符进行分情况讨论

    需要注意的是何时入栈何时出栈。

    代码:

    class Solution {
    public:
        string decodeString(string s) {
            stack<int> digits;
            stack<string> letters;
            int cnt = 0;
            string str("");
            for(int i = 0; i < s.size(); i++){
                if((s[i] - '0') >= 0 && (s[i] - '0' < 10)){
                    int temp = s[i] - '0';
                    cnt = cnt * 10 + temp;
                }
                else if( s[i] == '['){
                    digits.push(cnt);
                    letters.push(str);
                    cnt = 0;
                    str = "";
                }
                else if( s[i] == ']'){
                    int times = digits.top();
                    digits.pop();
                    string ls = str;
                    for(int i = 0; i< (times-1); i++){
                        str += ls;
                    }
                    string temp = letters.top();
                    letters.pop();
                    str = temp + str;
                }
                else{
                    str += s[i];
                }
            }
            return str;
        }
    };

    ---------------------------我是下一题分割线--------------------------------

     单调栈的应用:largest rectangle in histogram

    单调栈相关链接:单调栈总结

  • 相关阅读:
    丁丁杂想
    Tomcat5.5Ubuntu手记之编程
    插入递归引用Identity列的记录
    evolution错误Ubuntu手记之系统配置
    硬盘安装Ubuntu手记
    WAS安装及概念
    丁丁病了『续』
    web.config中配置字符串中特殊字符的处理
    新宝宝睡眠护理全方位【转】
    丁丁病了
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9119951.html
Copyright © 2011-2022 走看看