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.
解题思路:
题意找到最长有效括号的子串长度。求最大问题,第1想法就是动态计划,但是,通项公式真不好找。喜刷刷http://bangbingsyb.blogspot.jp/2014/11/leetcode-longest-valid-parentheses.html中有相干说明,我没有理解,
。
由因而括号问题,可以用栈来实现。这跟判断栈是不是有效不同。注意到,若某个右括号不与前面的某个左括号匹配,那末,这个右括号可以作为子串分割标记。大体思想是,若遇到左括号,无条件将左括号的下标入栈。若遇到右括号,若栈顶是左括号与之匹配,将左括号出栈,更新最大的长度值。若栈顶没有左括号与之匹配,将该右括号的下标入栈,作为分割字符。代码以下:
class Solution {
public:
int longestValidParentheses(string s) {
int len=s.length();
stack<int> st;
int maxLen=0;
for(int i=0; i<len; i++){
if(s[i]=='('){
st.push(i);
}else{
if(!st.empty()&&s[st.top()]=='('){
st.pop();
maxLen = max(maxLen,st.empty()?i+1:i-st.top());
}else{
st.push(i);
}
}
}
return maxLen;
}
};