码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Longest Valid Parentheses(Dynamic Programming)

时间:2015-03-14 16:55:18      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:动态规划

题目地址:https://leetcode.com/problems/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) {
        Stack<Integer> stack = new Stack<Integer>();
        int max = 0;
        int from = -1;
        char[] S = s.toCharArray();
        for(int i = 0;i < s.length(); ++i){
            if(S[i]==‘(‘) stack.push(i);
            else {//S[i] == ‘)‘
                if (stack.isEmpty()) from = i;//from指向最右边未匹配的‘)‘
                else{
                    stack.pop();
                    if(stack.isEmpty()) max = Math.max(max,i-from);
                    else max = Math.max(max,i-stack.peek());
                }
            }
        }
        return max;
    }
}

LeetCode -- Longest Valid Parentheses(Dynamic Programming)

标签:动态规划

原文地址:http://blog.csdn.net/jdplus/article/details/44260839

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!