您的位置:首页 > 其它

LeetCode Longest Valid Parentheses

2017-01-20 14:26 330 查看
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.

思路一:最没有技术含量的解题思路,暴力破解,时间复杂度O(N*3).该方法在s很长的时候,超过了leetcode的时间限制

代码如下:

class Solution {
public:
bool valid(string s)
{
int len = s.length();
stack<char> st;
for(int i=0;i<len;i++)
{
if(s[i] == '(')
st.push(s[i]);
else
{
if(st.empty())
return false;
else
st.pop();
}
}
return st.empty();
}

int longestValidParentheses(string s) {
int len = s.length();
int max = 0;
for(int i=0;i<len;i++)
for(int j=i+1;j<len;j+=2)
{
if(j-i+1 > max && valid(s.substr(i,j-i+1)))
max = j-i+1;
}
return max;
}
};


思路二:解题方法中的利器-动态规划。动态规划的关键就是状态转移方程:

当s[i] == ')', s[i-1] == '('时,dp[i] = dp[i-2]+2;

当s[i] == ')',s[i-1] == ')'时,如果s[i-dp[i]-1] == '(',那么dp[i] = dp[i-1]+dp[i-dp[i-1]-2]+2,

代码如下:

class Solution {
public:
int longestValidParentheses(string s) {
if(s=="")
return 0;
int len = s.length(),max=0;
int dp[len];
for(int i=0;i<len;i++)
dp[i] = 0;

for(int i=1;i<len;i++)
{
if(s[i] == ')')
{
if(s[i-1] == '(')
dp[i] = (i>=2?dp[i-2]:0) + 2;
else if( i-dp[i-1] > 0 && s[i-dp[i-1]-1] == '(')
{
dp[i] = dp[i-1] + (i-dp[i-1] >=2?dp[i-dp[i-1]-2]:0) + 2;
}
}
if(dp[i] > max)
max= dp[i];
}
return max;
}
};



思路三:通过栈结构来存放数据索引并进行判断序列是否合法

代码如下:

class Solution {
public:
int longestValidParentheses(string s) {
int len=s.length();
stack<int> st;
st.push(-1);
int max = 0;
for(int i=0;i<len;i++)
{
if(s[i] == '(')
st.push(i);
else
{
st.pop();
if(st.empty())
st.push(i);
else
{
if(i-st.top() > max)
max = i-st.top();
}
}
}
return max;
}
};



思路四:通过使用left和right两个变量来分别记录'('和')'的个数.第一次从左往右扫描,当left==right时,将2*left和max相比较,当right>left时,left=right=0,然后再从右往左扫描,当left==right时,将2*right和max相比较,当left>right时,left=right=0.为什么需要两次扫描呢? 例如,当s=“(()()(”时,从左往右扫描无法获得正确结果,但从左往右就可以。当s=“)()()”时,从左往右扫描就可以获得正确结果。

代码如下:

class Solution {
public:

int longestValidParentheses(string s) {
int left=0,right=0;
int max=0;
for(int i=0;i<s.length();i++)
{
if(s[i] == '(')
left++;
else
right++;

if(right ==left )
{
if(max < 2*left)
max=2*left;
}
else if(right >= left)
{
left = right =0;
}
}

left=right=0;
for(int i=s.length()-1;i>=0;i--)
{
if(s[i] == '(')
left++;
else
right++;

if(right ==left )
{
if(max < 2*left)
max=2*left;
}
else if(right <= left)
{
left = right =0;
}

}

return max;
}
};

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