题目:
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;
}
}