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.
Solutions:
这题看似简单,其实蛮复杂的。
从大神Eason Liu那里得到灵感,即遍历过程中标记该字符能否被配对,用一个辅助数组记录匹配结果。最后统计辅助数组中最长配对长度。
然后自己写的初版代码:
class Solution {
public:
int longestValidParentheses(string s) {
int size=s.size();
int length=0;
bool *flag = new bool[size];
memset(flag,0, size);
int i=0;
int pos=-1,prePos=-1;//the pos of previous unpaired '('
for(; i<size; ++i) {
if('(' == s[i]) {
prePos=pos;
pos = i;
}
else {
if(-1 != pos) {
flag[pos]=true;
flag[i]=true;
pos=prePos;
}
}
}
int cnt=0;
bool pre=false;
for(i=0; i<size; ++i) {
if(false == flag[i]) {
pre=false;
} else {
if(false == pre) {
cnt=1;
} else {
++cnt;
}
if( cnt > length) {
length=cnt;
}
pre=true;
}
}
return length;
}
};
长度较短的测试用例能通过,对于像")(((((()())()()))()(()))("就会错误,因为pre_pos只能动态回溯2个深度。
重新修改代码通过。
class Solution {
public:
int longestValidParentheses(string s) {
int size=s.size();
int length=0;
bool *flag = new bool[size];
memset(flag,0, size);
int i=0;
//int pos=-1,prePos=-1;//the pos of previous unpaired '('
stack<int> pos;
for(; i<size; ++i) {
if('(' == s[i]) {
pos.push(i);
}
else {
if(!pos.empty()) {
flag[pos.top()]=true;
flag[i]=true;
pos.pop();
}
}
}
int cnt=0;
bool pre=false;
for(i=0; i< size; ++i) {
cout<<flag[i]<<" ";
}
cout<<endl;
for(i=0; i<size; ++i) {
if(false == flag[i]) {
pre=false;
} else {
if(false == pre) {
cnt=1;
} else {
++cnt;
}
if( cnt > length) {
length=cnt;
}
pre=true;
}
}
return length;
}
};
http://www.cnblogs.com/remlostime/archive/2012/11/25/2787878.html提出另一种方法
struct Node
{
char c;
int index;
Node(){}
Node(char _c, int idx):c(_c), index(idx){}
};
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<Node> st;
st.push(Node(')', -1));
int ret = 0;
for(int i = 0; i < s.size(); i++)
{
char c = s[i];
if (c == '(')
st.push(Node(c, i));
else
{
Node node = st.top();
if (node.c == '(')
{
st.pop();
ret = max(ret, i - st.top().index);
}
else
st.push(Node(c, i));
}
}
return ret;
}
};