leetcode刷题-堆栈2
来源:互联网 发布:黑莓z10能用淘宝吗 编辑:程序博客网 时间:2024/06/07 20:51
package com.zwd.wkst.leetcode.stack;import java.util.Stack;/** * Created by zhangwd4 on 2017/11/2. * * 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 * * 题目大概意思就是给你一个字符串只有 “(”和“)”,求最长的开闭ok的括号组的字符串长度。 * * * */public class Solution1 { public int longestValidParentheses(String s) { int max =0; if( s== null || s.isEmpty()) { return max; } Stack<Character> stack = new Stack<>(); int temp = 0; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '('){ stack.push(c); } else{ if(stack.empty()){ temp = 0; continue; } else{ stack.pop(); temp+=2; } } System.out.println(i+","+temp); max = Math.max(temp,max); } return max; } public static void main(String arg[]){ int i = new Solution1().longestValidParentheses("()(()(()(()(()(()(()"); System.out.println(i); }}
这是我最初的版本:把问题看的有点简单了,一口气就写完了,漏洞百出啊。。。。。。。!!!!!
接下来我们来修改一下:
package com.zwd.wkst.leetcode.stack;import java.util.ArrayList;import java.util.List;import java.util.Stack;/** * Created by zhangwd4 on 2017/11/2. * * 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 * * 题目大概意思就是给你一个字符串只有 “(”和“)”,求最长的开闭ok的括号组的字符串长度。 * * * */public class Solution1 { public int longestValidParentheses(String s) { int max =0; if( s== null || s.isEmpty()) { return max; } Stack<Integer> stack = new Stack<>(); int pos = -1; for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '('){ stack.push(i); } else{ if(stack.isEmpty()){ pos = i; } else{ stack.pop(); if(stack.isEmpty()){ max = Math.max(max,i-pos); } else{ max=Math.max(max,i-stack.peek()); } } } } return max; } public static void main(String arg[]){ int i = new Solution1().longestValidParentheses("()(((()"); System.out.println(i); }}
阅读全文
0 0
- leetcode刷题-堆栈2
- leetcode刷题-堆栈
- leetcode刷题-堆栈3
- leetcode 堆栈
- LeetCode 之堆栈 stack
- 堆栈2
- 堆栈2
- LeetCode-20-Valid Parentheses(堆栈)-Easy
- 堆栈的心情(2)
- java堆栈2
- 堆栈啥的2
- Linux堆栈(2)
- 微软面试2 堆栈
- 堆栈内存分析2
- 堆栈初体验2
- 堆栈练习2:HDOJ1870
- 堆栈
- 堆栈
- STL 理解相等和等价的区别
- CSS3标准
- centos caffe编译问题汇总
- 函数调用过程中栈的压入和弹出
- SpringAOP原理之动态代理
- leetcode刷题-堆栈2
- ps 索引模式 导出变成了白色背景
- 设置导航栏的高度
- 未来物联网将如何改变我们的生活?
- Java并发编程:线程间协作的两种方式:wait、notify和Condition
- 如何使用hystrix 搭建分布式的高可用系统
- SSE2 指令
- 自动装机及ks.cfg&dhcp配置
- js处理大型数据崩掉解决方案