题目:
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) {
int max_len=0, last = -1;//标记有效括号开始前的位置
Deque<Integer> stack = new LinkedList<Integer>();
for(int i=0 ; i<s.length(); ++i)
{
//判断是否是"(",是则入栈,入栈的值是下标值,下面计算长度时有用。
if(s.charAt(i)=='(')
{
stack.addFirst(i);
}
else{
//当前元素是")",判断堆栈是否为空
if(stack.isEmpty())
{
//为空则是无效括号序列,更新last的值为从当前元素位置开始(以")"开始的无效括号)
last = i;
}
else {
//不为空,存在有效括号序列,栈顶元素出栈
stack.removeFirst();
if(stack.isEmpty())
{//一对有效括号判定完毕,计算有效括号长度,括号
max_len=Math.max(max_len, i-last);
}
else{
//以"("开始的无效括号,开始位置存在栈顶元素中,有效长度=当前下标-栈顶存储的下标
max_len= Math.max(max_len, i-stack.peekFirst());
}
}
}
}
return max_len;
}
}