Longest Valid Parentheses

来源:互联网 发布:配音软件手机软件 编辑:程序博客网 时间:2024/05/16 08:17

题目:

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.

分析:

简单

借助栈

参考代码:

感觉大神做这种简单题,就是大材小用啊,不过,再大的神也是从这种小题做出来的啊~

http://codeganker.blogspot.com/2014/03/longest-valid-parentheses-leetcode.html

public class Solution {    public int longestValidParentheses(String s) {    if(s==null || s.length()==0)        return 0;    LinkedList<Integer> stack = new LinkedList<Integer>();    int start = 0;    int max = 0;    for(int i=0;i<s.length();i++)    {        if(s.charAt(i)=='(')        {            stack.push(i);        }        else        {            if(stack.isEmpty())            {                start = i+1;            }            else            {                stack.pop();                max = stack.isEmpty()?Math.max(max,i-start+1):Math.max(max,i-stack.peek());            }        }    }    return max;}}


0 0
原创粉丝点击