20. Valid Parentheses
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.
class Solution {
public:
bool isValid(string s) {
stack<char> str;
for(auto c:s){
if(c=='('||c=='{'||c=='[')
str.push(c);
else if(c==')'||c=='}'||c==']'){
if(str.empty()) return false;
char top=str.top();
if(top=='('&&c==')' || top=='['&&c==']' || top=='{'&&c=='}') str.pop();
else return false;
}else return false;
}
return str.empty();
}
};
32. 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.
class Solution {
public:
int longestValidParentheses(string s) {
int maxLen=0;
int last=-1;
vector<int> stack;
for(int i=0;i<s.size();i++){
if(s[i]=='('){
stack.push_back(i);
}else if(s[i]==')'){
if(stack.size()>0){
stack.pop_back();
int len;
if(stack.size()==0){
len=i-last;
}else{
len=i-stack.back();
}
if(len>maxLen){
maxLen=len;
}
}else{
last=i;
}
}
}
return maxLen;
}
};