32. Longest Valid Parentheses
来源:互联网 发布:聚合数据看不懂 编辑:程序博客网 时间:2024/06/06 17:20
题目:
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.
分析:
对于字符串中每一个元素,只有两种取值,'('和')'
所以可分以下情况
- S[i]等于'('时,因为S[i-1]肯定不能与S[i]组合成有效的一对括号,可以不用考虑
- S[i]等于')'时,有两种情况
- s[i-1]等于'(',则dp[i]=dp[i-2]+2
- s[i-1]等于')',则dp[i]=dp[i-1]+2+dp[i-dp[i-1]-2]
因为题意中的Valid指连续的括号才算有效,所以需取最大值
代码:
class Solution {public: int longestValidParentheses(string s) { int size=s.size(); if (size<2) return 0; vector<int> dp(size,0); int cmax=0; for(int i=1;i<size;i++){ if(s[i]==')'){ if(s[i-1]=='(') { dp[i]=i-2>=0?(dp[i-2]+2):2; cmax=max(cmax,dp[i]); } else { if(i-dp[i-1]-1>=0&&s[i-dp[i-1]-1]=='(') { dp[i]=2+dp[i-1]+((i-dp[i-1]-2)>=0?dp[i-dp[i-1]-2]:0); cmax=max(cmax,dp[i]); } } } } return cmax; }};
阅读全文
0 0
- 32.Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- HDU
- UVA 1025 A Spy in the Metro(dp)
- 图像的上采样(upsampling)与下采样(subsampled)
- HDU敌兵布阵
- [编程题] 交错01串
- 32. Longest Valid Parentheses
- 关于java中的try-catch-finally语句和return
- ZZULIOJ【2178】GJJ来签到【水题】
- struts2.5之通配符使用报错
- [SDUT](3379)数据结构实验之查找七:线性之哈希表 ---哈希查找(查找)
- Elimination(DP)
- Java快排实现
- 原型函数的类型
- Hdu 1713 相遇周期