Longest Valid Parenthesis
来源:互联网 发布:淘宝网wap访客是 编辑:程序博客网 时间:2024/05/22 17:27
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.
11/1
An excellent problem to be done with DP in O(n) time.
use dp[i] to mean the length of the longest valid parentheses starting from i, so it is obvious that if s[i] is ')', dp[i] is 0
when s[i] is '(', check dp[i+1], if to the right of dp[i+1] + i+1 is a ')', that means the '(' at i and ')' at dp[i+1] + i+1 encircles a smaller valid parentheses of length dp[i+1], so dp[i] should be now dp[i+1] + 2
then again check the right of the ')' at dp[i+1]+i+1, and add the dp[dp[i+1]+i+2] if that is non-zero
public class Solution { public int longestValidParentheses(String s) { // dp[i] means the length of the longest matching parentheses starting from i int len = s.length(); int[] dp = new int[len]; for(int i=len-1; i>=0; i--){ char ch = s.charAt(i); if(ch == ')') dp[i] = 0; else if(ch == '('){ // check dp[i+1] if(i+1 < len){ int right = dp[i+1] + i+1; if(right < len && s.charAt(right) == ')'){ dp[i] = (dp[i+1] + 2); right++; if(right < len){ dp[i] += dp[right]; } } } } } int max = 0; for(int i=0; i<len; i++){ if(dp[i] > max) max = dp[i]; } return max; }}
- Longest Valid Parenthesis
- LeetCode - Valid Parenthesis
- Leetcode 20 Valid Parenthesis
- 【LeetCode】valid-parenthesis
- 678. Valid Parenthesis String
- 678. Valid Parenthesis String
- LeetCode678. Valid Parenthesis String
- [LeetCode]Valid Parenthesis String
- LeetCode-Valid Parenthesis String
- 678. Valid Parenthesis String
- Leetcode20-Valid Parenthesis
- leetcode 678 Valid Parenthesis String
- LWC 50:678. Valid Parenthesis String
- Parenthesis
- Parenthesis
- Parenthesis
- LeetCode: Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- Android 之ndk开发
- quick sort 的C++正确实现
- hdu5087——Revenge of LIS II
- Centos 6 安装python2.7.8
- web入门简介
- Longest Valid Parenthesis
- STAC测试报告:eXtremeDB 6.0 与 IBM Power8 的巅峰组合
- java中的Serializable接口到底是做什么用的?
- quick sort 算法 的C++实现
- 自己写的java连接mysql数据库的例子
- 桶排序(8.3)
- C++栈实现带括号的浮点型四则运算
- 分治思想的应用2
- Java获取随机数的方法