您的位置:首页 > 其它

leetcode 32. Longest Valid Parentheses

2016-08-05 12:50 441 查看
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.

分析:

给出一组括号,找出其中连续有效括号的最长长度。

for循环遍历每个括号,当前位置为i,index用于记录每段有效括号的起始位置。

(1)判断当前位置是否是左括号,如果遇到左括号,入栈。

(2)如果不是左括号,

1,判断栈是否为空,如果为空,将index指针后移。

2,如果栈不为空,弹出栈顶元素。

此时,如果栈为空,加上当前位置i的右括号可以构成一段有效的括号,最长为max(maxLen, i到index之间的距离),

如果栈不为空,说明栈顶后一位开始到当前位置可以构成一段有效的括号,那最长为max(maxLen, i到栈顶后一位的长度)。

public class Solution {
public int longestValidParentheses(String s) {
if (s == null){
return 0;
}

Stack<Integer> p = new Stack<Integer>();
int maxLen = 0;
int index = 0;

for (int i = 0; i < s.length(); i++){
if (s.charAt(i) == '('){
p.push(i);
}else{
if(p.isEmpty()){
index = i + 1;
}else{
p.pop();
if(p.isEmpty()){
maxLen = Math.max(i - index + 1, maxLen);
}else{
maxLen = Math.max(i - p.peek(), maxLen);
}
}
}
}
return maxLen;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: