*LeetCode-Longest Valid Parentheses
2015-10-11 05:35
141 查看
用一个stack记录每个char的位置 假如有可以凑成一对的就pop 没有就在里面留着 这样扫过一遍之后 留下的都是没有凑对的 然后找到所有没有凑对的之间的距离 就是之间连续的valid()的长度 注意最后一个stack里面的char和string最后的位置 以及stack里面第一个char和0位置之间的两个substring也要计入
还有一种是dp的做法
My solution uses DP. The main idea is as follows: I construct a array
longest[], for any longest[i], it stores the longest length of valid parentheses which is end at i.
And the DP idea is :
If s[i] is '(', set longest[i] to 0,because any string end with '(' cannot be a valid one.
Else if s[i] is ')'
If s[i-1] is '(', longest[i] = longest[i-2] + 2
Else if s[i-1] is ')' and s[i-longest[i-1]-1] == '(', longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]
For example, input "()(())", at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.
public class Solution { public int longestValidParentheses(String s) { if ( s == null || s.length() == 0 ) return 0; Stack <Integer> stack = new Stack <Integer> (); int length = 0; for ( int i = 0; i < s.length(); i ++ ){ if ( s.charAt ( i ) == '(' ) stack.push( i ); else { if ( !stack.isEmpty() && s.charAt(stack.peek()) == '(' ){ stack.pop(); } else stack.push ( i ); } } int right = s.length(); int left = 0; while ( !stack.isEmpty () ){ left = stack.pop(); length = Math.max ( length, right - left - 1); right = left; } length = Math.max( length, right ); return length; } }
还有一种是dp的做法
My solution uses DP. The main idea is as follows: I construct a array
longest[], for any longest[i], it stores the longest length of valid parentheses which is end at i.
And the DP idea is :
If s[i] is '(', set longest[i] to 0,because any string end with '(' cannot be a valid one.
Else if s[i] is ')'
If s[i-1] is '(', longest[i] = longest[i-2] + 2
Else if s[i-1] is ')' and s[i-longest[i-1]-1] == '(', longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]
For example, input "()(())", at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.
相关文章推荐
- 张益唐的有用性
- RabbitMQ实例教程:发布/订阅者消息队列
- 第五周学习任务报告
- LeetCode Course Schedule II
- Android ViewPager前两页显示空白
- Container With Most Water
- 84款 数据备份开源软件
- Rails读书笔记第二章
- 合并子目录所有文本文件的批处理
- excel减肥过滤广告
- excel 宏(VB)实现复制一列并按第二列的单元格长度排序
- Rails读书笔记第一章
- grunt快速上手(转)
- txt文档内容入mysql
- 一次熬夜解决的java乱码问题
- 3DMAX中CryEngine导出插件的配置方法
- 转基因食品与我国《食品安全法》
- 信息安全系统设计基础第四周学习总结
- ARX程序的升级及多版本编译须知
- 逆向破解学习二之<TraceMe>