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+栈

用一个栈记录左括号的索引,每次匹配到")"的时候,弹出对应的左括号,并且用这个索引计算括号的长度。

用currentMax记录当前最长的匹配串,它可以由多个有效的匹配累加而成,比如"()(())",currentMax = 2 + 4 = 6;或者等于当前最大的匹配,比如"()((())",currentMax = 4;

leftLen表示匹配当前")"时,得到的最长匹配是多少,比如"()(())",leftLen = 4;

totalMax是最终最长的匹配长度,每次匹配到")"的时候更新。

遇到'(',压栈

遇到')'有三种情况:

  • 类似"())"或者")"的情况,即这个右括号是多余的,判断的条件是此时栈为空,说明重新开始了,把currentMax置零;
  • 类似"()()"或者"()(())"的情况,即这个右括号是匹配的,并且它匹配以后栈空了,说明前面搜索到的"()"可以和当前搜索完的串"()"或者"(())"合并起来,把currentMax += i - leftLen;
  • 类似"(()"或者"()(()",即这个右括号是匹配的,但是匹配后栈里面还有左括号,需要继续匹配,此时说明前面搜索到的"()"还不能和当前的"()"合并(二者中间有未匹配的左括号)。所以leftLen就是此时能得到的最大匹配长度了。

代码如下:

 public class Solution {
public int longestValidParentheses(String s) {
if(s==null || s.length() == 0)
return 0; Stack<Integer> stack = new Stack <Integer>();
int totalMax = 0;
int currentMax = 0; for(int i = 0;i < s.length();i++){
if(s.charAt(i) == '('){
stack.push(i);
}
else{
//situations like ")" or "())"
if(stack.isEmpty()){
currentMax = 0;
}
else{
int leftPos = stack.pop();
int leftLen = i - leftPos + 1; //situations like "()" or "()()",then we can accumulate with parathesis before
if(stack.isEmpty()){
currentMax += leftLen;
leftLen = currentMax;
}
//situations like "(()" or "(()()",there is still left parathesis, so we can't accumulate
else {
leftLen = i - stack.peek();
}
totalMax = Math.max(totalMax, leftLen); }
} } return totalMax;
}
}

【leetcode刷题笔记】Longest Valid Parentheses的更多相关文章

  1. 刷题32. Longest Valid Parentheses

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

  2. 【leetcode刷题笔记】Valid Sudoku

    Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be ...

  3. 【leetcode刷题笔记】Valid Palindrome

    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignori ...

  4. 【leetcode刷题笔记】Valid Number

    Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...

  5. 【LeetCode每天一题】Longest Valid Parentheses(最长有效括弧)

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

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

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

  7. LeetCode (32) Longest Valid Parentheses

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

  8. LeetCode刷题笔记和想法(C++)

    主要用于记录在LeetCode刷题的过程中学习到的一些思想和自己的想法,希望通过leetcode提升自己的编程素养 :p 高效leetcode刷题小诀窍(这只是目前对我自己而言的小方法,之后会根据自己 ...

  9. 18.9.10 LeetCode刷题笔记

    本人算法还是比较菜的,因此大部分在刷基础题,高手勿喷 选择Python进行刷题,因为坑少,所以不太想用CPP: 1.买股票的最佳时期2 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. ...

随机推荐

  1. UINavigationController改变动画效果

    @interface UINavigationController (CustomTransition) - (void) pushWithCustomAnimation:(UIViewControl ...

  2. URL检测脚本

    #!/bin/bash# filename : 8_5_1.sh function usage(){ echo "usage:$0 url" exit 1} function ch ...

  3. stage3D基础三------什么是AGAL(转)

    原文链接 http://www.adobe.com/cn/devnet/flashplayer/articles/hello-triangle.html 在本文中,你将研究一个能够正常运行的基于Sta ...

  4. Sphinx之配置文件

    # # Sphinx configuration file sample # # WARNING! While this sample file mentions all available opti ...

  5. <mark>元素----黄色背景

     当需要引用其他人的内容,或者想要重点标注一段文本时可以使用<mark>元素.这样浏览器会给<mark>中的文本添加黄色背景. 效果图如下:原文:HTML5 - 使用<m ...

  6. C语言基础知识【存储类】

    C 存储类1.存储类定义 C 程序中变量/函数的范围(可见性)和生命周期.这些说明符放置在它们所修饰的类型之前autoregisterstaticextern2.auto 只能用在函数内,即 auto ...

  7. Android 适配(drawable文件夹)图片适配(二)

    参考自(https://blog.csdn.net/myoungmeng/article/details/54090891) Android资源文件存放: android的drawable文件一共可以 ...

  8. lua元表(简单例子)

    Set = {} Set.mt = {}--定义普通的表作为元表,为了避免命名污染直接放在Set内部 function Set.new(t) local set = {} setmetatable(s ...

  9. 【BZOJ3510】首都 LCT维护子树信息+启发式合并

    [BZOJ3510]首都 Description 在X星球上有N个国家,每个国家占据着X星球的一座城市.由于国家之间是敌对关系,所以不同国家的两个城市是不会有公路相连的. X星球上战乱频发,如果A国打 ...

  10. MFC添加菜单资源与菜单执行函数的两种命令形式

    添加资源->新建一个菜单资源->选择相应的对话框 菜单的执行函数命令形式: COMMAD 是指点击菜单后的执行命令 UPDATE_COMMAND_UI 是指点击菜单后菜单状态的函数