乘风破浪:LeetCode真题_032_Longest Valid Parentheses

一、前言

这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次最简单的方法当然也不例外。

二、Longest Valid Parentheses

2.1 问题

2.2 分析与解决

    通过分析题意,这里我们有几种方法:

       暴力算法:

public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push('(');
} else if (!stack.empty() && stack.peek() == '(') {
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
public int longestValidParentheses(String s) {
int maxlen = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 2; j <= s.length(); j+=2) {
if (isValid(s.substring(i, j))) {
maxlen = Math.max(maxlen, j - i);
}
}
}
return maxlen;
}
}

但是对于比较长的字符串就会超时了,因为时间复杂度为O(n~3):

      第二种方法:动态规划

      我们使用dp[i]表示前面的i个字符的最大有效括号长度,因此dp[0]=0,dp[1]=0,于是就可以开始推出一个公式来计算了。

public class Solution {
public int longestValidParentheses(String s) {
int maxans = 0;
int dp[] = new int[s.length()];
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == ')') {
if (s.charAt(i - 1) == '(') {
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
} else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {
dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
}
maxans = Math.max(maxans, dp[i]);
}
}
return maxans;
}
}

   方法三:通过我们的方法,堆栈,很清晰很容易的解决了问题。

public class Solution {

    public int longestValidParentheses(String s) {
int maxans = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.empty()) {
stack.push(i);
} else {
maxans = Math.max(maxans, i - stack.peek());
}
}
}
return maxans;
}
}

     当然还有其他的方法,在此不再赘述。

三、总结

在我们遇到括号的时候一定要想到使用堆栈来解决,当然动态规划是比较难的,我们也要理解和使用。

乘风破浪:LeetCode真题_032_Longest Valid Parentheses的更多相关文章

  1. leetCode练题——20. Valid Parentheses

    1.题目 20. Valid Parentheses——Easy  Given a string containing just the characters '(', ')', '{', '}',  ...

  2. 乘风破浪:LeetCode真题_022_Generate Parentheses

    乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...

  3. 乘风破浪:LeetCode真题_020_Valid Parentheses

    乘风破浪:LeetCode真题_020_Valid Parentheses 一.前言 下面开始堆栈方面的问题了,堆栈的操作基本上有压栈,出栈,判断栈空等等,虽然很简单,但是非常有意义. 二.Valid ...

  4. 乘风破浪:LeetCode真题_036_Valid Sudoku

    乘风破浪:LeetCode真题_036_Valid Sudoku 一.前言 有的时候对于一些基础知识的掌握,对我们是至关重要的,比如ASCII重要字符的表示,比如一些基本类型的长度. 二.Valid ...

  5. 乘风破浪:LeetCode真题_041_First Missing Positive

    乘风破浪:LeetCode真题_041_First Missing Positive 一.前言 这次的题目之所以说是难,其实还是在于对于某些空间和时间的限制. 二.First Missing Posi ...

  6. 乘风破浪:LeetCode真题_040_Combination Sum II

    乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...

  7. 乘风破浪:LeetCode真题_039_Combination Sum

    乘风破浪:LeetCode真题_039_Combination Sum 一.前言     这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...

  8. 乘风破浪:LeetCode真题_038_Count and Say

    乘风破浪:LeetCode真题_038_Count and Say 一.前言     这一道题目,很类似于小学的问题,但是如果硬是要将输入和结果产生数值上的联系就会产生混乱了,因此我们要打破思维定势. ...

  9. 乘风破浪:LeetCode真题_037_Sudoku Solver

    乘风破浪:LeetCode真题_037_Sudoku Solver 一.前言 这次我们对于上次的模型做一个扩展并求解. 二.Sudoku Solver 2.1 问题 2.2 分析与解决     这道题 ...

随机推荐

  1. Hibernate关联关系映射之一对一(主键关联)

    在业务成的域模型中,类和类之间最普遍的关系就是关联关系,而关联也是有方向的. 就以例子来说明:一个人对应一张身份证.对其进行增删改. 对于人在数据创建表的时候,我们就给他两个字段,一个是id号,一个就 ...

  2. linux----之tcpdump小用

    1.通过抓包大致确定访问量 #time tcpdump -nn -i eth0 'tcp[tcpflags] = tcp-syn' -c 10000 >/dev/null 根据real时间判断访 ...

  3. 【SpringBoot系列2】SpringBoot整合Redis

    前言: 真的越来越喜欢SpringBoot了,这是SpringBoot学习系列之一. 正文: 1:首先在pom文件中添加依赖,记得是spring-boot-starter-data-redis,不是s ...

  4. Netty 源码剖析之 unSafe.read 方法

    目录: NioSocketChannel$NioSocketChannelUnsafe 的 read 方法 首先看 ByteBufAllocator 再看 RecvByteBufAllocator.H ...

  5. 在MVC应用程序中使用jQuery的验证

    呵呵,觉得很久没有写博客了,均是工作忙于公司的ERP系统,这是正确的,因为这才是真正的工作. 今天想写点在MVC应用程序中,使用jQuery来验证.在进行之前,还是先回看一下<MVC会员注册&g ...

  6. T-SQL建索引

    USE database GO   ------------开始----------- ALTER TABLE [name] DROP CONSTRAINT 主键约束    ----删除主键约束 IF ...

  7. Java - "JUC" ReentrantLock释放锁

    Java多线程系列--“JUC锁”04之 公平锁(二) 释放公平锁(基于JDK1.7.0_40) 1. unlock() unlock()在ReentrantLock.java中实现的,源码如下: p ...

  8. Python paramiko ssh 在同一个session里run多个命令

    import threading, paramiko strdata='' fulldata='' class ssh: shell = None client = None transport = ...

  9. 使用PHPExcel实现数据批量导入到数据库

    此例子只使用execel2003的.xls文档,若使用的是其他版本,可以保存格式为“Execel 97-2003 工作簿(*.xls)”即.xls文件类型即可! 功能说明:只能上传Excel2003类 ...

  10. Mysql数据库 的库表简易操作

    一. 库的操作 1.创建数据库 创建数据库: create database 库名 charset utf8;   charset uft8  可选项 1.2 数据库命名规范: 可以由字母.数字.下划 ...