Longest Valid Parentheses

My Submissions

Question Solution 
Total Accepted: 47520 Total Submissions: 222865 Difficulty: Hard

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.

#include<iostream>
#include<string>
using namespace std;
#define NUM 350 class Solution { public:
int longestValidParentheses(string s)
{
int len = s.length();
if (len < ) return ;
//int**dp= (int **)new int[10000][10000];
//int** isValid=(int **)new int[10000][10000];
//int max = 0;
//memset(dp, 0, 10000 * 10000 * sizeof(int));
//memset(isValid, 0, 10000 * 10000 * sizeof(int));
int dp[NUM][NUM];
int isValid[NUM][NUM];
int max = ;
memset(dp, , NUM * NUM * sizeof(int));//会影响到结果输出
memset(isValid, , NUM * NUM * sizeof(int));
for (int i = ; i < s.length(); ++i)
{
for (int j = i - ; j >= ; --j)
{
if (s[j] = '('&&s[i] == ')')//情况一
{
int temp = ;
for (int k = j + ; k < i; ++k)
{
if (isValid[j][k] && isValid[k + ][i])
temp = ;
}
if (i == j + || dp[j + ][i - ] || temp)
{
isValid[j][i] = ;
dp[j][i] = i - j + ;
max = max > dp[j][i] ? max : dp[j][i];
}
else
{
isValid[j][i] = ;
dp[j][i] = dp[j + ][i] > dp[j][i - ] ? dp[j + ][i] : dp[j][i - ];
}
}
else if (s[j] == '('&&s[i] == '(')//情况二
{
isValid[j][i] = ;
dp[j][i] = dp[j][i - ];
}
else if (s[j] == ')'&&s[i] == ')')//情况三
{
isValid[j][i] = ;
dp[j][i] = dp[j + ][i];
}
else//情况四
{
isValid[j][i] = ;
dp[j][i] = dp[j + ][i - ];
}
}
}
return max;
}
}; int main()
{
Solution test;
string s1 = ")(())()";
int res = test.longestValidParentheses(s1);
cout << res << endl;
return ;
}

无奈,只好搜索求助大神,dp:

这道题可以用一维动态规划逆向求解。假设输入括号表达式为String s,维护一个长度为s.length()的一维数组dp[],数组元素初始化为0。 dp[i]表示从s[i]到s[s.length - 1]最长的有效匹配括号子串长度。则存在如下关系:
dp[s.length - 1] = 0;从i - 2 到0逆向求dp[],并记录其最大值。
若s[i] == '(',则在s中从i开始到s.length - 1计算s[i]的值。这个计算分为两步,通过dp[i + 1]进行的(注意dp[i + 1]已经在上一步求解):
在s中寻找从i + 1开始的有效括号匹配子串长度,即dp[i + 1],跳过这段有效的括号子串,查看下一个字符,其下标为j = i + 1 + dp[i + 1]。若j没有越界,并且s[j] == ‘)’,则s[i ... j]为有效括号匹配,dp[i] =dp[i + 1] + 2。
在求得了s[i ... j]的有效匹配长度之后,若j + 1没有越界,则dp[i]的值还要加上从j + 1开始的最长有效匹配,即dp[j + 1]。

O(n)

 int longestValidParentheses(string s) {
// Note: The Solution object is instantiated only once.
int slen = s.length();
if(slen<)return ;
int max = ;
int* dp = new int[slen];
memset(dp,,sizeof(int)*slen); for(int i=slen-; i>=;i--)
{
if(s[i]=='(')
{
int j = i++dp[i+];
if(j<slen && s[j]==')')
{
dp[i]=dp[i+]+;
int k = ;
if(j+<slen)k=dp[j+];
dp[i] += k;
}
max = max>dp[i]?max:dp[i];
}
}
delete[] dp;
return max;
}

自己的理解大神思想精髓并用对称顺序实现:

 class Solution {
public:
int longestValidParentheses(string s) {
int max=;
int len=s.size();
int *dp=new int[len];//dp[i]表示从s[0]到s[i-1]最长的字符有效匹配长度
for(int i=;i<len;i++)
dp[i]=;
for(int i=;i<s.size();i++)
{
if(s[i]==')')
{
int j=i-dp[i-]-;
if(j>=&&s[j]=='(')
{
dp[i]=dp[i-]+;
int k=;
if(j->=)
k=dp[j-];
dp[i]+=k;
}
max=dp[i]>max?dp[i]:max;
}
}
delete[] dp;
return max;
}
};

这段代码当真高明啊!!

Longest Valid Parentheses 每每一看到自己的这段没通过的辛酸代码的更多相关文章

  1. [LeetCode] 032. Longest Valid Parentheses (Hard) (C++)

    指数:[LeetCode] Leetcode 指标解释 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 032. Lon ...

  2. [LeetCode] Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  3. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  4. leetcode 32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  5. 【leetcode】Longest Valid Parentheses

    Longest Valid Parentheses Given a string containing just the characters '(' and ')', find the length ...

  6. 【leetcode】 Longest Valid Parentheses (hard)★

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  7. [LeetCode] Longest Valid Parentheses 动态规划

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  8. Java for LeetCode 032 Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  9. 【Longest Valid Parentheses】cpp

    题目: Given a string containing just the characters '(' and ')', find the length of the longest valid ...

随机推荐

  1. (整理)SQL server 2012 中文乱码与5030错误

    安装2012后,一直没注意到中文的问题.直到有一天,突然发现字段内容竟然是“??”,然后一通查,原来是排序规则需要改变: 选择数据库->右键属性->选项,将排序规则改成“Chinese_P ...

  2. 五、selecting with the API

    1. 命令通常从selection list中得到input, 调用MGlobal::getActiveSelectionList(MSelectionList &dest, bool ord ...

  3. 使用JDBC处理Oracle大数据

    一.Oracle中大数据处理 在Oracle中,LOB(Large Object,大型对象)类型的字段现在用得越来越多了.因为这种类型的字段,容量大(最多能容纳4GB的数据),且一个表中可以有多个这种 ...

  4. php判断 !==false

    测试 if($res !== false){ echo "未定义通过<br>"; }else{ echo "未定义不通过<br>"; } ...

  5. Visual Studio 2013 编译CEF步骤

    If you'd like to build the Chromium Embedded Framework (a wrapper for Chromium, for creating browser ...

  6. CGI、FastCGI和PHP-FPM浅析

    这段时间对Nginx+PHP-FPM的概念和机制一直不太清晰,趁着同事的分享和看过的几篇博文和资料,重新将思路处理一下. 首先,PHP-FPM(FastCGI Process Manager: Fas ...

  7. linux网络完全与防护

    7.1 网络封包联机进入主机的流程   7.1.1 封包进入主机的流程 1.经过防火墙的分析 iptables 主要功能是封包过滤 主要分析TCP/IP的封包表头来进行过滤的机制 分析的是OSI的第二 ...

  8. underscore 笔记

    //reduce是汇总 递归 var perDesc=[ {name: "haha", "email": "haha@email.com"} ...

  9. JavaWEB域对象

    PageContext: ServletRequest: HttpSession: ServletContext: void setAttribute(String name, Object valu ...

  10. dubbo+zookeeper例子

    0.原理   Alibaba有好几个分布式框架,主要有:进行远程调用(类似于RMI的这种远程调用)的(dubbo.hsf),jms消息服务(napoli.notify),KV数据库(tair)等.这个 ...