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. iOS开发--一些UITabBarItem属性的设置[转]

    1.改变UITabBarItem 字体颜色 [[UITabBarItemappearance]setTitleTextAttributes:[NSDictionary dictionaryWithOb ...

  2. Android:去掉默认的标题bar

    要使用自己定义的bar,只需要在layout文件中添加:<include layout="@layout/actionbar" />;当然你需要新建一个actionba ...

  3. 【Robot Framework】robot framework 学习以及selenium、appnium、requests实践(一)

    话说之前自己写了个selenium的自动化框架,然后又研究了下RF,觉得RF这种基于关键字驱动的框架更为容易上手,当然在做一些比较繁琐的验证时,似乎还不是太灵活,不如自己写几行python来的实惠(也 ...

  4. Ibatis 测试出SQL

    String sql = Brg.Global.Map.BaseBatis.GetRuntimeSql("select_T_JewelleryProductType", _Mode ...

  5. Scala伴生类和伴生对象

    单例对象与类同名时,这个单例对象被称为这个类的伴生对象,而这个类被称为这个单例对象的伴生类.伴生类和伴生对象要在同一个源文件中定义,伴生对象和伴生类可以互相访问其私有成员.不与伴生类同名的单例对象称为 ...

  6. avalon2的后端渲染实践

    avalon2为了提高性能,采用全新的架构,四层架构,其中一层为虚拟DOM. 虚拟DOM的一个好处是能大大提高性能,另一个好处是能过错整描述我们的页面结构.因此在非浏览器环境下,虚拟DOM也能正常运行 ...

  7. 样式link属性media用法--媒体类型查询

    引用外部样式使用link 你可能想针对将要显示页面的设备类型(桌面PC.笔记本电脑.平板电脑.手机或者甚至页面的印刷版本)来调整页面的样式,可以利用一个media属性, 在<link>元素 ...

  8. [vivado系列]设置Xilinx Documention Navigator

    版本:2015.1 ------------------------------------------ 这是一个很便利FPGA工程师的文档整理收纳神器. 针对个人使用上的习惯,进行简单的2项设置. ...

  9. eval 函数的应用 (去除包装在列表外面的引号)

    a="[u'ANDROID-5a9ac5c22ad94e26b2fa24e296787a35', u'0', 0, 0, 0, 1]" 此时的a是一个字符串,目的是要去掉a上面的引 ...

  10. Keynote of Python III

    [Keynote of Python III] 1.许多大型网站是用Python开发的,例如YouTube.Instagram,还有国内的豆瓣.很多大公司,包括Google.Yahoo等,甚至NASA ...