先写两个用栈做的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:
- Open brackets must be closed by the same type of brackets.
- 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;
}
};