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. Mono addin 学习笔记 3

    典型的基于Mono addin插件框架的应用程序有以下一个部分组成: 1. 主应用程序:提供了一系列的扩展点(Extension Point)供其他应用进行扩展: 2. 扩展插件: 其部署结构图如下为 ...

  2. /etc/resolv.conf overwritten. Redhat/Centos

    Prevent /etc/resolv.conf from being blown away by RHEL/CentOS after customizing If you are using RHE ...

  3. Jmeter学习一:Jmeter性能测试环境搭建(Windows下)

    最近刚开始接触Jmeter性能测试,现总结环境搭建如下: 一.windows安装JDK步骤与环境变量配置: 1.先将下载的JDK安装到其默认目录:C:\Program Files\Java\jdk1. ...

  4. mac安装chromedriver报错

    运行提示:Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/c ...

  5. JSON之Asp.net MVC C#对象转JSON,DataTable转JSON,List转JSON,JSON转List,JSON转C#对象

    一.JSON解析与字符串化 JSON.stringify() 序列化对象.数组或原始值 语法:JSON.stringify(o,filter,indent) o,要转换成JSON的对象.数组或原始值 ...

  6. java中常用数据类型转换器

    /** * 把String转换成long * * @param src 要转换的String * @param def 转换失败时返回此值 * @return 转换好的long */ public s ...

  7. Mybatis保存数据时事务问题

    今天不小心在sqlplus中用for update ,然后事务没提交,结果在项目中一直保存不进去数据,找了很久发现是sqlplus中的事务没提交,哎,这种问题真得避免啊,一定要细心啊!

  8. django中的静态文件管理

    一个站点通常需要保存额外的文件,比如图片   css样式文件   js脚本文件 ,在django中,倾向于将这些文件称为 静态文件.django提供了django.contrib.staticfile ...

  9. sql按字段值进行统计

    用group by 如有个student表里有性别sex来统计 select sex,count(*) from student group by sex;

  10. Cadence UVM基础视频介绍(UVM SV Basics)

    Cadence关于UVM的简单介绍,包括UVM的各个方面.有中文和英文两种版本. UVM SV Basics 1 – Introduction UVM SV Basics 2 – DUT Exampl ...