地址:http://oj.leetcode.com/problems/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) {
if(s.empty())
return 0;
vector<bool>flag(s.length(), false);
for(int i = 0; i<s.length(); ++i)
{
if(s[i]==')')
{
int j = i-1;
while(j>=0 && flag[j])
--j;
if(j>=0 && s[j]=='(')
{
flag[i] = flag[j] = true;
}
}
}
int ans = 0, len = 0;
for(int i = 0; i<flag.size(); ++i)
{
if(flag[i])
{
while(i<flag.size() && flag[i])
{
++len;
++i;
}
ans = max(ans, len);
len = 0;
}
}
return ans;
}
};