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);    }}


原创粉丝点击