栈:先进后出
一、括号匹配
看到括号的匹配,首先应该想到的就是用栈来解决问题。
1. 题目描述:
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
2. 分析:
- 如果为左括号则入栈
- 如果为右括号:
-
- 栈为空或者与栈顶的左括号不匹配,
return false
- 栈为空或者与栈顶的左括号不匹配,
-
- 否则,弹出与该右括号相匹配的栈顶元素,
st.pop()
- 否则,弹出与该右括号相匹配的栈顶元素,
3. 题解:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char ch : s)
{
if(ch == '(' || ch == '[' || ch == '{')
st.push(ch);
else if(ch == ')')
{
if(st.empty() || st.top() != '(')
return false;
st.pop();
}
else if(ch == ']')
{
if(st.empty() || st.top() != '[')
return false;
st.pop();
}
else if(ch == '}')
{
if(st.empty() || st.top() != '{')
return false;
st.pop();
}
}
if(st.empty())
return true;
return false;
}
};
二、分配律(双栈)
两类元素分别创建一个栈
1. 题目描述
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
输入:s = “3[a2[c]d]”
输出:“accdaccdaccd”
2. 分析
解决分配律的问题,数字和字符串分别创建一个栈,记录当前的情况
- 遍历整个字符串
- 遇到
[
则将num
和res
入栈,并清空num
和res
- 遇到
]
,计算当前形如2[c]
的组合字符串,并拼接在栈顶的字符串的后面保存a2[c]
的格式,res = st.top() + num * res
3. 题解
class Solution {
public:
string decodeString(string s) {
stack<int> st_num;
stack<string> st_str;
string res = "";
int num = 0;
for(char ch : s)
{
if(isdigit(ch))
num = num * 10 + ch - '0';
else if(isalpha(ch))
res += ch;
else if(ch == '[')
{
st_num.emplace(num);
num = 0;
st_str.push(move(res));
}
else
{
for(int i = 0; i < st_num.top(); i++)
st_str.top() += res;
res = st_str.top();
st_num.pop();
st_str.pop();
}
}
return res;
}
};
三、单调栈
单调栈的使用情况:如果需要找到左边或者右边第一个比当前位置数大或者小的数,则可以考虑使用单调栈,栈内的元素是单调的;单调栈的题目如每日温度,矩形面积,接雨水等等
1. 题目描述
739 . 每日温度
84 .
柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
输入:heights = [2,1,5,6,2,3]
输出:10
解释:最大的矩形为图中红色区域,面积为 10
2. 分析
计算并比较当前柱状图的高度能勾勒出的矩形,使用单调栈
,当前柱状图高度小于栈顶柱状图高度时,计算该柱状图能勾勒出的矩形,此矩形的高为height[st.top()]
,宽为该柱状图出栈st.pop()
后i -st.top()-1
,此时i -st.top()-1
宽度内的柱状图的高度都大于等于当前柱状图高度;
为了能够计算最后一个柱状图可以勾勒得矩形面积,故在height
最后面添加一个0,height.emplace_back(0)
;并为了可以计算最低得柱状图勾勒得矩形面积(最低得矩形计算面积时需要st.pop()
,此时若st.pop()
后栈为空则找不到矩形左边界,而最低的矩形面积计算时左边界为最左边),需要在height
最开始添加一个0,height.insert(height.begin(), 0)
3. 题解
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
heights.insert(heights.begin(), 0);
heights.emplace_back(0);
stack<int> st;
int res = 0;
st.push(0);
for(int i = 1; i < heights.size(); i++)
{
while(heights[i] < heights[st.top()])
{
int cur_height = heights[st.top()];
st.pop();
int width = i - st.top() - 1;
res = max(res, cur_height * width);
}
st.push(i);
}
return res;
}
};