Leetcode总结 栈专题

在这里插入图片描述

class Solution {
public:
    bool isValid(string s) {
        stack<char> stk;
        for(auto c : s)
        {
            if(c == ')')
            {
                if(stk.empty() || stk.top() != '(')
                    return false;
                stk.pop(); //匹配 弹出去    
            }
            else if(c == ']')
            {
                if(stk.empty() || stk.top() != '[')
                    return false;
                stk.pop();
            }
            else if(c == '}')
            {
                if(stk.empty() || stk.top() != '{')
                    return false;
                stk.pop();
            }
            else stk.push(c);
        }
        return stk.empty();
    }
};

在这里插入图片描述

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size(), res = 0;
        if(!n) return 0;
        vector<int> left_max(n), right_max(n);
        left_max[0] = height[0];
        for(int i = 1; i < n; i ++)
            left_max[i] = max(left_max[i - 1], height[i]);

        right_max[n - 1] = height[n - 1];
        for(int i = n - 2; ~i; i --)
            right_max[i] = max(right_max[i + 1], height[i]);

        for(int i = 0; i < n; i ++)
            res += min(left_max[i], right_max[i]) - height[i];
        return res;
    }
};
class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size(), ans = 0;
        stack<int> stk;
        for(int i = 0; i < n; i ++)
        {
            while(!stk.empty() && height[i] > height[stk.top()])
            {
                int top = stk.top();
                stk.pop();
                if(stk.empty()) break;
                ans += (i - stk.top() - 1) * (min (height[stk.top()], height[i]) - height[top]);
            }
            stk.push(i);
        }
        return ans;
    }
};

在这里插入图片描述

class Solution {
public:
    string simplifyPath(string path) {
        path += '/';//在最后加入斜杆
        string res, s;
        for(auto c : path)
        {
            if(res.empty()) res += c;
            else if(c != '/') s += c; //一串字符
            else //右斜杆
            {
                if(s == "..") //   ../返回上一级目录
                {
                    if(res.size() > 1) 
                    {
                        res.pop_back(); //去掉上一级右斜杆
                        while(res.back() != '/')
                            res.pop_back();
                    }
                }
                else if(s != "" && s != ".") // ./当前目录
                    res += s + '/';
                s = "";
            }
        }
        if(res.size() > 1) res.pop_back(); //最后斜杆去掉
        return res;
    }
};

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    int largestRectangleArea(vector<int>& heights) {
        int n = heights.size(), res = 0;
        heights.push_back(-1); //在数组末尾添加高度-1 
        stack<int> stk;
        for(int i = 0; i <= n; i ++)
        {
            while(!stk.empty() && heights[i] < heights[stk.top()])
            {
                int cur = stk.top();
                stk.pop();
                if(stk.empty())
                    res = max(res, heights[cur] * i);
                else
                    res = max(res, heights[cur] * (i - stk.top() - 1));
            }
            stk.push(i);
        }
        return res;
    }
};

在这里插入图片描述

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        //求出每一层的 heights[] 然后传给上一题的函数就可以了
        int n = matrix.size(), m, res = 0;
        if(n == 0) return 0;
        m = matrix[0].size();
        vector<int> heights(m + 1, 0);
        heights[m] = -1;
        for(int i = 0; i < n; i ++)
        {
            for(int j = 0; j < m; j ++)
                if(matrix[i][j] == '0')
                    heights[j] = 0;
                else
                    heights[j] ++;
            stack<int> stk;
            for(int j = 0; j <= m; j ++)
            {
                while(!stk.empty() && heights[j] < heights[stk.top()]){
                    int cur = stk.top();
                    stk.pop();
                    if(stk.empty())
                        res = max(res, heights[cur] * j);
                    else    
                        res = max(res, heights[cur] * (j - stk.top() - 1));
                }
                stk.push(j);
            }
        }
        return res;
    }
};

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
        dfs(root);
        return res;
    }

    void dfs(TreeNode* root)
    {
        if(!root) return;
        if(root->left) dfs(root->left);
        res.push_back(root->val);
        if(root->right) dfs(root->right);
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stk;
        TreeNode* now = root;
        while(now || !stk.empty())
        {
            while(now){
                stk.push(now);
                now = now->left;
            }
            if(!stk.empty())
            {
                now = stk.top();
                stk.pop();
                res.push_back(now->val);
                now = now->right;
            }
        }
        return res;
    }
};

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> get_val(vector<TreeNode*> level)
    {
        vector<int> res;
        for(auto &u : level)
            res.push_back(u->val);
        return res;
    }
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(!root) return res;
        vector<TreeNode*> level;
        level.push_back(root);
        res.push_back(get_val(level));
        bool zigzag = true;
        while(1)
        {
            vector<TreeNode*>newlevel;
            for(auto &u : level)
            {
                if(u->left) newlevel.push_back(u->left);
                if(u->right) newlevel.push_back(u->right);
            }
            if(newlevel.size())
            {
                vector<int>tmp = get_val(newlevel);
                if(zigzag) reverse(tmp.begin(), tmp.end());
                res.push_back(tmp);
                level = newlevel;
            }
            else break;
            zigzag = !zigzag;
        }
        return res;
    }
};

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int>res;
    vector<int> preorderTraversal(TreeNode* root) {        
        if(!root) return res;
        res.push_back(root->val);
        if(root->left) preorderTraversal(root->left);
        if(root->right) preorderTraversal(root->right);
        return res;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> stk;
        vector<int> res;
        TreeNode* p = root;
        while(p || !stk.empty())
        {
            while(p)
            {
                res.push_back(p->val);
                stk.push(p);
                p = p->left;
            }
            p = stk.top()->right;
            stk.pop();
        }
        return res;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int>res;
    vector<int> preorderTraversal(TreeNode* root) {        
        if(!root) return res;
        res.push_back(root->val);
        if(root->left) preorderTraversal(root->left);
        if(root->right) preorderTraversal(root->right);
        return res;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int>res;
        if(!root) return res;
        stack<TreeNode*>stk;
        TreeNode*now = root;
        while(now || !stk.empty())
        {            
            while(now)
            {
                res.push_back(now->val);
                stk.push(now);
                now = now->left;
            }
            if(!stk.empty())
            {
                now = stk.top();
                stk.pop();
                now = now->right;
            }
        }
        return res;
    }
};

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int>res;
    vector<int> postorderTraversal(TreeNode* root) {
        if(!root) return res;
        if(root->left) postorderTraversal(root->left);
        if(root->right) postorderTraversal(root->right);
        res.push_back(root->val);
        return res;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> stk;
        TreeNode* p = root, * lastVisited = NULL;
        while(p || !stk.empty())
        {
            while(p)
            {
                stk.push(p);
                p = p->left;                
            }
            p =stk.top();
            if(p->right == NULL || p->right == lastVisited) //右儿子为空或者已经遍历过
            {
                stk.pop();
                res.push_back(p->val);
                lastVisited = p;
                p = NULL;
            }
            else p = p->right;
        }
        return res;
    }    
};

在这里插入图片描述

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int>stk;
        for(auto &t : tokens)
            if(t == "+" || t == "-" || t == "*" || t == "/")
            {
                int a = stk.top();
                stk.pop();
                int b = stk.top();
                stk.pop();
                if(t == "+") stk.push(a + b);
                else if(t == "-") stk.push(b - a);
                else if(t == "*") stk.push(a * b);
                else stk.push(b / a);
            }
            else stk.push(atoi(t.c_str()));
        return stk.top();
    }
};

在这里插入图片描述

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> stackValue;
    stack<int> stackMin;
    MinStack() {

    }
    
    void push(int x) {
        stackValue.push(x);
        if(stackMin.empty() || x <= stackMin.top())
            stackMin.push(x);
    }
    
    void pop() {
        int x = stackValue.top();
        stackValue.pop();
        if(x == stackMin.top()) stackMin.pop();
    }
    
    int top() {
        return stackValue.top();
    }
    
    int getMin() {
        return stackMin.top();
    }
};

/**
 * 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();
 */
class MinStack {
public:
   /** initialize your data structure here. */
   stack<int>stackValue;
   stack<int>stackMin;
   MinStack() {

   }
   
   void push(int x) {
       stackValue.push(x);
       if(stackMin.empty())
           stackMin.push(x);
       else
       {
           int tmp = stackMin.top();
           if(x < tmp)
               stackMin.push(x);
           else
               stackMin.push(tmp);
       }
   }
   
   void pop() {
       stackValue.pop();
       stackMin.pop();
   }
   
   int top() {
       return stackValue.top();
   }
   
   int getMin() {
       return stackMin.top();
   }
};

/**
* 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();
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值