Longest Valid Parentheses
来源:互联网 发布:淘宝上卖的vr怎么样 编辑:程序博客网 时间:2024/05/29 19:45
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.
一维DP。dp[i]表示[i, n-1]的最长距离,所以i从n-2开始逆向dp。
如果s[i]=‘(’,那么跳过中间dp[i+1] 已经求出的最长距离,到 j=i+1+dp[i+1],如果dp[j]为‘)’且j<n,那么dp[i]=dp[i+1]+2.
接下来还需要一步计算:如果j+1<n,[i, j]已经求出了最大距离,还需要加上dp[j+1]. 相当于最终的值=新匹配的()-> 2+dp[i+1]+dp[j+1]
int longestValidParentheses(string s){ int dp[65536]; int longest=0; int n=s.size(); memset(dp, 0, 65536); for(int i=n-2; i>=0; i--) { if(s[i]=='(') { int j=i+1+dp[i+1]; if(j<n && s[j]==')') { dp[i]=dp[i+1]+2; if(j+1<n) dp[i]+=dp[j+1]; } } longest=max(longest, dp[i]); } return longest;}
0 0
- LeetCode: Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Longest Valid Parentheses
- Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- LeetCode31:Longest Valid Parentheses
- longest valid parentheses
- Longest Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- Longest Valid Parentheses
- Longest Valid Parentheses
- Longest Valid Parentheses
- TLB和cache
- R语言进行数据预处理
- mysql开启远程连接
- 学习开源 Senparc.Weixin.MP SDK 微信公众平台开发教程(二):成为开发者
- 阿里云服务器增加FTP用户并且绑定目录
- Longest Valid Parentheses
- java中HashMap详解
- jQuery aiax 无刷新提交表单
- 黑马程序员19.GUI
- 如何解决:Android中 Error generating final archive: Debug Certificate expired on 10/09/18 16:30 的错误
- 页面新增
- 用集算器写一个八皇后
- 离不离,什么时候离职,离职的原因
- C/C++--set排序