首页 > 其他 > 详细

Longest Valid Parentheses

时间:2015-05-11 12:26:40      阅读:196      评论:0      收藏:0      [点我收藏+]

Longest Valid Parentheses

问题:

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 int longestValidParentheses(String s) {
        if(s==null || s.length()==0)    return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int max = 0;
        
        for(int i=0; i<s.length(); i++)
        {
            if(stack.isEmpty() || s.charAt(stack.peek())==‘)‘ || s.charAt(i)==‘(‘) stack.push(i);
            else
            {
                stack.pop();
                int index = stack.isEmpty()? -1 : stack.peek();
                max = Math.max(max,i-index);
            }
        }
        return max;
    }
}
View Code

他人代码:

技术分享
public int longestValidParentheses(String s) {
    char[] S = s.toCharArray();
    int[] V = new int[S.length];
    int open = 0;
    int max = 0;
    for (int i=0; i<S.length; i++) {
        if (S[i] == ‘(‘) open++;
        if (S[i] == ‘)‘ && open > 0) {
            V[i] = 2 + V[i-1] + (i-2-V[i-1] > 0 ? V[i-2-V[i-1]] : 0);
            open--;
        }
        if (V[i] > max) max = V[i];
    }
    return max;
}
View Code

学习之处:

  • 不知道这道题为什么在leetcode上hard的难度,思路很容易想,代码很容易些,也一遍就AC了
  • 想的越多,最后写出来的代码越简洁
  • 看别人的代码才发现,这道题的另外一个解法使用动态规划来解, V[i-1] is its previous consecutive parentheses, i-2-V[i-1] is the position right outside this big "( ... )" part. So check if previous big "(...)" is a valid one. 
  • 改掉不好的习惯 day by day

Longest Valid Parentheses

原文:http://www.cnblogs.com/sunshisonghit/p/4493853.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!