Leetcode 棧

20. Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: “()”
Output: true
Example 2:

Input: “()[]{}”
Output: true
Example 3:

Input: “(]”
Output: false
Example 4:

Input: “([)]”
Output: false
Example 5:

Input: “{[]}”
Output: true
C++

class Solution {
public:
    bool isValid(string s) {
        stack<char> r;
        for(int i=0;i<s.length();i++)
        {
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')
                r.push(s[i]);
            else
            {
                if(r.empty())
                    return false;
                char t=r.top();
                r.pop();
                if(s[i]==')'&&t!='(') return false;
                if(s[i]==']'&&t!='[') return false;
                if(s[i]=='}'&&t!='{') return false;
            }
        }
        if(!r.empty()) return false;
        return true;
    }
};

155. Min Stack
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.
設計一個最小棧,實現push, pop, top, getMin四個功能。相比原來的棧多了一個功能,可以返回當前棧內的最小值
解法:使用2個棧,棧1記錄進來的數,棧2記錄目前的最小值。當有新數push進來的時候,如果棧2爲空或者這個數小於棧2頂上的值,就把這個數推入棧2。當pop的數正好等於最小值時,說明當前棧內的最小值變化了,要彈出這個最小值,記錄的下一個最小值來到棧頂。
C++

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x<=s2.top())
            s2.push(x);
    }
    
    void pop() {
        if(s1.top()==s2.top()) s2.pop();
        s1.pop();
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.top();
    }
    private:
    stack<int> s1,s2;
};

224. Basic Calculator
Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

Example 1:

Input: “1 + 1”
Output: 2
Example 2:

Input: " 2-1 + 2 "
Output: 3
Example 3:

Input: “(1+(4+5+2)-3)+(6+8)”
Output: 23
JAVA(難)

class Solution {
    public int calculate(String s) {
         if (s.length() == 0) {
            return 0;
        }
        s = "(" + s + ")";
        int[] pos = {0};
        return eval(s, pos);
    }
 
    private static int eval(String s, int[] pos) {
        int val = 0, i = pos[0], sign = 1, num = 0;
        while(i < s.length()) {
            char c = s.charAt(i);
            switch(c) {
                case '+': val = val + sign * num; num = 0; sign = 1; i++; break;
                case '-': val = val + sign * num; num = 0; sign = -1; i++; break;
                case '(': pos[0] = i + 1; val = val + sign * eval(s, pos); i = pos[0]; break;
                case ')': pos[0] = i + 1; return val + sign * num; 
                case ' ': i++; continue;
                default : num = num * 10 + c - '0'; i++;
            }
        }
        return val;
    }
}

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.
Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
這道題讓我們用棧來實現隊列。棧和隊列的核心不同點就是棧是先進後出,而隊列是先進先出,那麼我們要用棧的先進後出的特性來模擬出隊列的先進先出。那麼怎麼做呢,其實很簡單,只要我們在插入元素的時候每次都都從前面插入即可,比如如果一個隊列是1,2,3,4,那麼我們在棧中保存爲4,3,2,1,那麼返回棧頂元素1,也就是隊列的首元素,則問題迎刃而解。所以此題的難度是push函數,我們需要一個輔助棧tmp,把s的元素也逆着順序存入tmp中,此時加入新元素x,再把tmp中的元素存回來,這樣就是我們要的順序了,其他三個操作也就直接調用棧的操作即可
C++

class MyQueue {
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack<int> tmp;
        while(!s.empty())
        {
            tmp.push(s.top());
            s.pop();
        }
        s.push(x);
        while(!tmp.empty())
        {
            s.push(tmp.top());
            tmp.pop();
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int r=s.top();
        s.pop();
        return r;
    }
    
    /** Get the front element. */
    int peek() {
        return s.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return s.empty();
    }
    private:
      stack<int> s;
};

496. Next Greater Element I
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
Example 2:
Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
For number 2 in the first array, the next greater number for it in the second array is 3.
For number 4 in the first array, there is no next greater number for it in the second array, so output -1.
題目其實很簡單,關鍵在於理解:
以nums1 = [4, 1, 2],nums2 = [1, 3, 4, 2]爲例,
nums1[0] = 4,對應爲nums2[2],在nums2中,4右邊沒有大於4的值,因此返回-1
nums1[1] = 1,對應爲nums2[0],在nums2中,1右邊第一個大於1的值爲3,因此返回3
分析:使用棧,從後往前遍歷nums2[i],每當棧不爲空的時候,一直出棧直到遇到比nums2[i]大的數字停止。設立一個map<int, int> m,存儲nums2中每一個元素以及它對應的下一個最大元素構成的映射。如果停止後棧爲空就將m[nums2[i]]標記爲-1,否則就寫棧的棧頂元素~
最後將Nums1中出現的每一個元素對應的map的值放入result數組中返回~
C++

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        stack<int> s;
        map<int,int> m;
        for(int i=nums2.size()-1;i>=0;i--)
        {
            while(!s.empty() && s.top()<=nums2[i])
                s.pop();
            m[nums2[i]]=s.empty()?-1:s.top();
            s.push(nums2[i]);
        }
        for(int i=0;i<nums1.size();i++)
            result.push_back(m[nums1[i]]);
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章