leetcode 32. Longest Valid Parentheses——(use stack)
2016-06-07 09:47
369 查看
import java.util.Stack; //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. public class Solution { public static void main(String[] args) { String input = "(())()"; int output = longestValidParentheses(input); System.out.println(output); } public static int longestValidParentheses(String s) { if(s.length() == 0){ return 0; } Stack<Integer> stack = new Stack<Integer>(); int lengthBefore = 0; //为括号之前有多少已经匹配成功的括号串 int max = 0; if(s.charAt(0) == '('){ stack.push(lengthBefore); } for(int i = 1;i<s.length();i++){ if(s.charAt(i) == '('){ stack.push(lengthBefore); //将'('前已经成功匹配的有效括号串push入栈中 lengthBefore = 0; }else{ if(stack.isEmpty()){ lengthBefore = 0; }else{ lengthBefore = lengthBefore+stack.pop()+2; //')'成功匹配后,有效括号串的长度为:2+匹配成功的'('之前的有效括号串长度+本反括号')'之前的有效括号串长度 } max = Math.max(max, lengthBefore); } } return max; } }
相关文章推荐
- Java中用内存映射处理大文件的实现代码
- 用 jQuery 取得 Div 的宽度与高度(Width, Padding, Border, Margin)
- 各种常用校验方法的源代码
- spring MVC 配置详解
- C++异常对象三种方式传递的综合比较
- Python 守护线程
- 解决springmvc乱码问题
- Java基础之网页400 401 405 500错误
- python监控文件或目录变化
- ViewFlipper图片切换器
- NSIS安装包制作
- windows下php连接sqlserver2008
- 获取实体属性名称(Property)和DisplayName属性名称(Attribute)
- typedef函数指针用法
- 想知道82%的人都不知道的技能吗?点击查看……
- UML类图画法及其之间的几种关系
- php 中文分词使用
- Hibernate使用sql语句查询
- AQS(AbstractQueuedSynchronizer)源码分析
- Reveal + 越狱真机查看第三方app的UI结构