题目链接:https://leetcode.com/problems/longest-valid-parentheses/description/

题目大意:找出最长的括号匹配的子串长度。例子:"(()("长度是2;"()()(())"长度是8

解法一:利用三层for循环,逐一的找每一个子串,并判断每一个子串是否是括号匹配的。很遗憾,超时了。代码如下:

     public int longestValidParentheses(String s) {
int res = 0;
for(int i = 0; i < s.length(); i++) {//逐一查看每一个子串
for(int j = i + 2; j <= s.length(); j += 2) {
int cnt = parentheses(s.substring(i, j));
if(res < cnt) {
res = cnt;
}
}
}
return res;
}
//判断是否是括号匹配的
public static int parentheses(String s) {
Stack<Character> st = new Stack<Character>();
int cnt = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ')') {
if(!st.isEmpty() && st.peek() == '(') {
cnt++;
st.pop();
}
else {
return 0;
}
}
else {
st.push(c);
}
}
if(!st.isEmpty()) {
return 0;
}
return cnt * 2;
}

解法二(借鉴):用栈存储左括号下标,而不是'('左括号。如果是'(',则将下标压栈。如果是')',则查看栈的情况,如果栈空,则记录下一个子串开始的位置下标(即i+1);如果非空,则查看栈中元素情况,如果只有一个'(',则弹出计数子串长度,如果有多个'(',则计数到目前为止的匹配的子串长度情况。或者同时压栈存储左括号和右括号下标,当遇到')',则查看栈顶元素,如果是'(',则计数,否则压栈。这两种方法都是o(n)的时间复杂度。代码如下(耗时26ms):

第一种压栈左括号下标的方法:

 public int longestValidParentheses(String s) {
Stack<Integer> st = new Stack<Integer>();//存'('下标
int res = 0, lastIndex = 0, length = s.length();
for(int i = 0; i < length; i++) {
char c = s.charAt(i);
if(c == '(') {//如果是'(',将下标压栈
st.push(i);
}
else {//如果是')',分情况讨论
if(st.isEmpty()) {//如果为空,则出现')'没有'('匹配的情况,则当前子串结束,下一个子串的开始位置即是当前子串结束的下一个位置
lastIndex = i + 1;
}
else {//如果非空,可能出现两种情况:'()'或'(())'
st.pop();
if(st.isEmpty()) {//如果为空,则说明栈中没有'('需要匹配
res = Math.max(res, i - lastIndex + 1);
}
else {//如果非空,则当前栈中还有'('存在
res = Math.max(res, i - st.peek());
}
}
}
}
return res;
}

第二种压栈左括号和右括号下标的方法(基本与上面第一种一样):

     public int longestValidParentheses(String s) {
Stack<Integer> st = new Stack<Integer>();
int res = 0, length = s.length();
for(int i = 0; i < length; i++) {
if(s.charAt(i) == '(') {//左括号压栈下标
st.push(i);
}
else {//遇到右括号
if(st.isEmpty()) {//如果栈空,则压栈右括号下标
st.push(i);
}
else {
if(s.charAt(st.peek())== '(') {//如果栈顶元素是左括号,则匹配,退栈计数子串长度
st.pop();
res = Math.max(res, (i - (st.isEmpty() ? -1 : st.peek())));
}
else {//如果栈顶元素是右括号,则压栈右括号下标
st.push(i);
}
}
}
}
return res;
}

解法三:利用dp。首先dp[i] 表示从s[i]往前推最长能匹配的子串,换句话说,就是到s[i]为止的最长匹配子串后缀。那么当对于下面几种情况进行分析:

1. s[i] ==’(’     s[i]为左括号,dp[i]=0这个很好理解。
2. s[i] ==’)’  这就要分情况了
  a) 如果s[i-1]是’(’说明已经完成了一次匹配,子串长度为2,但是还要加上dp[i-2]的大小,也就是当前匹配的这对括号前面的最长匹配长度,它们是相连的。
  b) 如果s[i-1]是’)’这样不能匹配,则需要考虑s[i-1-dp[i-1]]的情况了,如果s[i-1-dp[i-1]]是一个左括号,则与当前右括号匹配,那么此时我们令dp[i]=dp[i-1]+2,这个2就是刚刚匹配的左右括号。最后还要把dp[i-2-dp[i-1]](即与当前括号')'匹配的'('前面一个位置的dp长度,它们是相连的)值加起来,把相连的最大长度求出来。代码如下(耗时20ms):

     public int longestValidParentheses(String s) {
int length = s.length();
int[] dp = new int[length];
int res = 0;
for(int i = 0; i < length; i++) {
dp[i] = 0;
if(s.charAt(i) == ')' && (i - 1) >= 0) {
if((i - 1) >= 0 && s.charAt(i - 1) == '(') {//如果前一个位置与当前括号')'匹配
dp[i] = 2;//暂且只计算匹配的'('')'
if(i - 2 >= 0) {//加上与')'匹配的'('前一个位置的dp匹配长度
dp[i] += dp[i - 2];
}
}
else {//如果前一个位置与当前括号'('不匹配
if((i - 1 - dp[i - 1]) >= 0 && s.charAt(i - 1 - dp[i - 1]) == '(') {//查看【前一个位置下标-匹配数】之后的字符与当前括号')'是否匹配
dp[i] = dp[i - 1] + 2;//如果匹配,则在前一个位置匹配数的情况下+2,即加上刚与当前')'匹配的左右括号数量
if(i - 2 - dp[i - 1] >= 0) {//加上与')'匹配的'('前一个位置的dp匹配长度
dp[i] += dp[i - 2 - dp[i - 1]];
}
}
}
}
res = Math.max(res, dp[i]);
}
return res;
}

32.Longest Valid Parentheses---dp的更多相关文章

  1. 刷题32. Longest Valid Parentheses

    一.题目说明 题目是32. Longest Valid Parentheses,求最大匹配的括号长度.题目的难度是Hard 二.我的做题方法 简单理解了一下,用栈就可以实现.实际上是我考虑简单了,经过 ...

  2. [Leetcode][Python]32: Longest Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 32: Longest Valid Parentheseshttps://oj ...

  3. leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、

    20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...

  4. 32. Longest Valid Parentheses (Stack; DP)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  5. [LeetCode] 32. Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  6. 32. Longest Valid Parentheses

    题目: Given a string containing just the characters '(' and ')', find the length of the longest valid ...

  7. leetcode解题报告 32. Longest Valid Parentheses 用stack的解法

    第一道被我AC的hard题!菜鸡难免激动一下,不要鄙视.. Given a string containing just the characters '(' and ')', find the le ...

  8. 32. Longest Valid Parentheses (JAVA)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  9. leetcode 32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  10. Java [leetcode 32]Longest Valid Parentheses

    题目描述: Given a string containing just the characters '(' and ')', find the length of the longest vali ...

随机推荐

  1. 【51Nod1773】A国的贸易 FWT+快速幂

    题目描述 给出一个长度为 $2^n$ 的序列,编号从0开始.每次操作后,如果 $i$ 与 $j$ 的二进制表示只差一位则第 $i$ 个数会加上操作前的第 $j$ 个数.求 $t$ 次操作后序列中的每个 ...

  2. Yii2 控制器单独向view(layout)传值

    Yii2,layout中使用Controller的值,Controller向layout传值的两种方式. yii2中在通过Controller向layout中传值,layout中访问Controlle ...

  3. 【数学】【P5076】 Tweetuzki 爱整除

    Description 对于一个数 \(k\),找到任意一个 \(x\),满足 \(0~\leq~k~\leq~x~\leq~10^{18}\) 且对于任意一个 \(x\) 进制数,把该数字各数位上的 ...

  4. go日期时间函数+常用内建函数+错误处理

    日期时间函数 // 时间日期函数包 import "time" // 1. 当前时间 time.Now()-->time.Time类型 // 2. now:=time.Now ...

  5. syntax error: non-declaration statement outside function body

    在函数外部使用形如:name:="mark"这样语句会出现 syntax error: non-declaration statement outside function bod ...

  6. poj3469 Dual Core CPU

    Dual Core CPU Time Limit: 15000MS   Memory Limit: 131072K Total Submissions: 25576   Accepted: 11033 ...

  7. AI技术说:人工智能相关概念与发展简史

    作为近几年的一大热词,人工智能一直是科技圈不可忽视的一大风口.随着智能硬件的迭代,智能家居产品逐步走进千家万户,语音识别.图像识别等AI相关技术也经历了阶梯式发展.如何看待人工智能的本质?人工智能的飞 ...

  8. 关于Linux运维的一些题目总结

    一.有文件file1 1.查询file1里面空行的所在行号 awk ‘{if($0~/^$/)print NR}’ fileorgrep -n ^$ file |awk ‘BEGIN{FS=”:”}{ ...

  9. js获取本周、上周的开始结束时间

    这两天在做一个报表体统,其中涉及到了一个根据本周,上周,本月,上月的时间来进行查询的问题,在这个我就教一下大家怎么实现,大家如果有更好的实现方法的,我也希望大家能说出来,我们交流交流. 首先呢,我写了 ...

  10. HDU 2608 底数优化分块 暴力

    T(n) as the sum of all numbers which are positive integers can divied n. and S(n) = T(1) + T(2) + T( ...