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.
我的思路:
设置matched数组记录每一位是否配对成功
while
{
找到未配对成功的第一个)位于位置i
找到距离i最近的左边的未配对成功的j
配对i和j,设置matched[i]=matched[j]=1
}
找到matched数组中最长的连续1,即所求
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> matched(s.length(),0);
for(int i=0;i<s.length();i++)
{
if(s[i]==')')
{
int j=i-1;
while( j>=0 && !(matched[j]==0 && s[j]=='('))
{
j--;
}
if(j>=0)
{
//match i and j
matched[i]=matched[j]=1;
}
}
}
//find the longest consecutive substring 11111... in matched
int longest=0;
for(int i=0;i<matched.size();i++)
{
int tmplong=0;
while(i<matched.size() && matched[i]==0) {i++;}
while(i<matched.size() && matched[i]==1)
{
tmplong++;
i++;
}
if(tmplong>longest) longest=tmplong;
}
return longest;
}
};
worst case: O(n^2), example: "(((((((((((((((((((((((()))))))))))))))))))))))))"
思路2:
Keep a stack and only store the unmatched "(".
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<int> pStack;
int lastleft=0;//keep track of the start point of the current longest valid parenthese
int longest=0;
for(int i=0;i<s.length();i++)
{
if(s[i]=='(')
{
pStack.push(i);
}
else
{
if(!pStack.empty())
{
pStack.pop();
//now pStack.top() the previous index of the start point of the longest valid parenthese
if(!pStack.empty())
longest=max(longest,i-pStack.top());
else
longest=max(longest,i-lastleft+1);
}
else{
//mismatched ) found, the longest string must end
//update the start of the first valid parenthtes
lastleft=i+1;
}
}
}
return longest;
}
};