标签:turn ann put match ace mat ide long idp
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.
思路
The workflow of the solution is as below.
int longestValidParentheses(string s) { stack<int>st; if(s.length()<=1)return 0; for(int i=0;i<s.length();i++) { if(st.empty())st.push(i); else { if(s[i] ==‘(‘)st.push(i); else if(s[i]==‘)‘&&s[st.top()]==‘(‘)st.pop(); else st.push(i); } } if(st.empty()) return s.length(); int a =s.length(),b =0; int longest = 0; while(!st.empty()) { b=st.top(); st.pop(); longest = max(longest,a-b-1); a = b; } longest = max(longest,a); return longest; }
参考:
https://discuss.leetcode.com/topic/2289/my-o-n-solution-using-a-stack
[leetcode-32-Longest Valid Parentheses]
标签:turn ann put match ace mat ide long idp
原文地址:http://www.cnblogs.com/hellowooorld/p/7044761.html