1. Valid Parenthese
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
如果最后栈的值不为0,则不为Parenthese
bool isValid(string s) {
if(s.size()%2 == 1 || s.size() == 0)
return false;
vector<char> sta;
sta.push_back(s[0]);
for(int i=1; i< s.size(); i++){
if(s[i] == '(' || s[i]=='[' || s[i]=='{'){
sta.push_back(s[i]);
continue;
}
char current = sta.back();
if(s[i] == ')' && current != '(' )
return false;
if(s[i] == ']' && current != '[')
return false;
if(s[i] == '}' && current != '{')
return false;
sta.pop_back();
}
if(sta.size() != 0 ) return false;
return true;
}
2. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
int longestValidParentheses(string s) {
int result = 0;
int lastleft = 0;
if(s.size()<2) return result;
stack<int> sta;
for(int i=0; i<s.size(); i++){
if(s[i]=='('){
sta.push(i);
}
else{
if(!sta.empty()){
sta.pop();
if(!sta.empty())
result = max(result, i-sta.top());
else
result = max(result,i-lastleft+1);
}else{
lastleft = i+1;
}
}
}
return result;
}
3. Largest Rectangle in Histogram
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, fi