Longest Valid Parentheses
2015-07-21 22:08
357 查看
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.
求最长的括号匹配的子串,如()(()))的匹配长度为6。
解法:
维护一个栈,栈底值为上次匹配失败的位置
首先初始放一个-1入栈代表上次匹配失败的地方为-1
依次扫描字符
若为'(',将位置放入栈中
若为')',若栈中元素大于1个,则代表有'('可匹配,更新最优值,否则更新栈底
显然,对于任意一个部分最长子串,其最后一个字符更新时取的是上一次匹配失败的位置,
故所有部分最长子串取得最优结果
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.
求最长的括号匹配的子串,如()(()))的匹配长度为6。
解法:
维护一个栈,栈底值为上次匹配失败的位置
首先初始放一个-1入栈代表上次匹配失败的地方为-1
依次扫描字符
若为'(',将位置放入栈中
若为')',若栈中元素大于1个,则代表有'('可匹配,更新最优值,否则更新栈底
显然,对于任意一个部分最长子串,其最后一个字符更新时取的是上一次匹配失败的位置,
故所有部分最长子串取得最优结果
public class Solution { public int longestValidParentheses(String s) { int count=0; Stack<Integer> sk=new Stack<Integer>(); sk.push(-1); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='(') sk.push(i); else{ if(sk.size()>1){ sk.pop(); int tmp=sk.peek(); count=Math.max(count, i-tmp); }else{ sk.pop(); sk.push(i); } } } return count; } }
相关文章推荐
- 广搜专题-1001
- ubuntu下svn创建多个仓库
- cocos2d-x3.2 在Windows下打包Android平台APK
- JS正则替换掉小括号及内容
- 关于ios的UIwindows and UIviewcontroller
- GP数据库笔记—表结构查询,表占用空间查询
- JS正则替换掉小括号及内容
- JS正则替换掉小括号及内容
- [leetcode] Trapping Rain Water
- CGlib-打造无入侵的类代理
- Sort List
- 项目需求分析
- WPF DatePicker只显示年和月
- javascript 深拷贝
- 3、DNS服务器功能(正向、反向解析)
- 2. ansible常用模块
- tyvj1728 普通平衡树
- 阿里云主机从公司突然就访问不了
- In-app Billing 概述
- 黑马程序员——Java基础---面向对象