32. Longest Valid Parentheses
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
题意:
统计连续序列中互补括号的最长序列长度
思路:
非常巧妙的解法,
利用栈存放每个左括号的索引,遇到右括号就出栈。
巧妙之处:首先在栈中存放-1,如果-1也出栈了,就说明有多于的未匹配的右括号,这时候考虑放入右括号的索引,用该索引代替右括号的位置
时间复杂度:O(N)
class Solution {
public:
//太巧妙了
int longestValidParentheses(string s) {
// stack<char> S
stack<int> S;
S.push(-1);
int ans=0;
for(int i=0;i<s.size();i++){
if(s[i]==')'){
S.pop();
if(S.empty()){
S.push(i);//栈空了,说明有多于的右括号,这时候利用右括号代替-1的位置
}
else{
ans=max(ans,i-S.top());
}
}
else{
S.push(i);//放入左括号位置
}
}
return ans;
}
};
// 1.()()(() 2*2=4
//2. ()()(()) 4*2=8
84. Largest Rectangle in Histogram
Given a rows x cols binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
题意:
统计最大的矩形面积
思路:
参考84. Largest Rectangle in Histogram的解题思路。此题可以看成是该题的加强版。
大体思路均是维护一个单调栈,保证每行的高度值只被遍历过一次。
时间复杂度:O(N^2)
class Solution {
public:
//单调栈
//一行一行扫
//从0~i行的面积可以采用单调栈来解决
int maximalRectangle(vector<vector<char>>& matrix) {
if(!matrix.size() || (!matrix[0].size())) return 0;
int m=matrix.size();
int n=matrix[0].size();
vector<int> h(n+1,0),pre(n+1,0); //最后一列补0
int ans=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]=='1') h[j]=pre[j]+1;
else h[j]=0;
pre[j]=h[j];
}
//单调栈 统计每行的情况
stack<int> S; //记录高度值对应的索引
for(int j=0;j<n+1;j++){//最后一列为0
while(!S.empty() && h[S.top()]>h[j]){
int tmp_h=h[S.top()];
S.pop();
int tmp_l=S.empty()?-1:S.top();
ans=max(ans,tmp_h*(j-1-tmp_l));
}
S.push(j);
}
}
return ans;
}
};