棧stack、單調棧Monotone Stack

先寫兩個用棧做的LeetCode算法題:


1、 Valid Parentheses有效的括號

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
class Solution {
public:
    bool isValid(string s) {
        if(s.size()==0)return true;
        stack<char>sta;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')sta.push(s[i]);
            else
            {
                if(sta.empty())return false;
                if(sta.top()!='(' && s[i]==')')return false;
                if(sta.top()!='[' && s[i]==']')return false;
                if(sta.top()!='{' && s[i]=='}')return false;
                sta.pop();
            }
        }
        return sta.empty();
    }
};

2、Evaluate Reverse Polish Notation逆波蘭表達式求值PRN

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

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

 


單調棧看起來挺簡單,但是應用起來有點難。

單調棧就是棧內元素單調遞增或者單調遞減的棧,單調棧只能在棧頂操作。

單調棧的一大優勢就是線性的時間複雜度,所有的元素只會進棧一次,而且一旦出棧後就不會再進來了。

單調遞增棧可以找到左起第一個比當前數字小的元素單調遞減棧可以找到左起第一個比當前數字大的元素

 

3、接雨水


class Solution {
public:
    int trap(vector<int>& height) {
        stack<int> st;
        int i = 0, res = 0, n = height.size();
        while (i < n) {
            if (st.empty() || height[i] <= height[st.top()]) {
                st.push(i++);
            } else {
                int t = st.top(); st.pop();
                if (st.empty()) continue;
                res += (min(height[i], height[st.top()]) - height[t]) * (i - st.top() - 1);
            }
        }
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章