您的位置:首页 > 其它

[leetcode] Longest Valid Parentheses

2015-08-20 10:39 302 查看
from : https://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.

思路1:

使用栈和flag数组,每次匹配出栈的时候,将对应的flag位置记录为true。最后在flag中找出最长连续的为true的一段即可。
public class Solution {
public int longestValidParentheses(String s) {
int len = s.length();
if(0 == len || "".equals(s)) return 0;
Stack<Integer> idxes = new Stack<Integer>();
boolean flag[] = new boolean[len];

for(int i=0; i<len; ++i) {
char c = s.charAt(i);
if(idxes.empty() || '(' == c) {
idxes.push(i);
} else if(')' == c) {
if('(' == s.charAt(idxes.peek())) {
flag[i] = flag[idxes.pop()] = true;
} else {
idxes.push(i);
}
}
}
int max = 0;
for(int i=0; i<len; ++i) {
if(flag[i]) {
int j = i;
while(i<len && flag[i]) {
++i;
}
if(i-j > max) {
max = i-j;
}
}
}
return max;
}
}

思路2:

用栈,下标本身可以记录长度。

class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size(), longest = 0;
if(0 == len) return 0;
stack<int> idxes;

for(int i=0; i<len; ++i) {
char c = s[i];
if(idxes.empty() || '(' == c) idxes.push(i);
else if(')' == c) {
if('(' == s[idxes.top()]) {
idxes.pop();
longest = max(idxes.empty()?i+1:i - idxes.top(), longest);
} else {
idxes.push(i);
}
}
}

return longest;
}
};


思路3:

DP。

数组dp[i]表示s中从i开始到最后,可以匹配的最长的括号个数。那么,i+dp[i](如果比s.size())就是下一个没有被匹配到的括号。倒着进行dp。

初始值:

dp[n-1] = 0;

递推关系:

如果s[i] == ')', 不可能从它开始有匹配的字符串,故不处理。

如果s[i]=='(',那么找到下一个没有被匹配的位置,j=i+1+dp[i+1],如果这个位置为')',正好匹配一对,那么dp[i] = dp[i+1]+2,且如果下一个位置j的下一个位置(如果j+1<n),那么可以将从i~j和j+1到j+dp[j+1]-1折两段连起来;

class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size(), max = 0;
int *fd = new int[len];
for(int i=0; i<len; ++i) {
fd[i] = 0;
}
for(int i=len-2; i>=0; --i) {
if(s[i]=='(') {
// find indice that i should match
int j = i+1+fd[i+1];
if(j < len && s[j] == ')') {
fd[i] = fd[i+1]+2;
if(j+1 < len && fd[j+1] > 0) {
fd[i] += fd[j+1];
}
if(fd[i] > max) {
max = fd[i];
}
}
}
}
delete[] fd;
return max;

}
};


public class Solution {
public int longestValidParentheses(String s) {
int len = s.length(), max = 0;
int[] fd = new int[len];
for(int i=len-2; i>=0; --i) {
if(s.charAt(i)=='(') {
// find indice that i should match
int j = i+1+fd[i+1];
if(j < len && s.charAt(j)==')') {
fd[i] = fd[i+1]+2;
if(j+1 < len && fd[j+1] > 0) {
fd[i] += fd[j+1];
}
if(fd[i] > max) {
max = fd[i];
}
}
}

}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: