您的位置:首页 > 其它

32. Longest Valid Parentheses

2016-09-18 10:17 288 查看
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.

思路: 用栈来实现. 用栈存储左括号的下标, 对字符串进行从左到右的遍历,当遇到左括号时,将其下标压栈;当遇到右括号时,先判断栈是否为空,若是空,则将变量left更新为当前右括号下标,表示字符串匹配从left右边开始;若栈不为空,弹出一个,即左括号,若弹出后,栈为空,比较当前最大值和当前下标与left的差值的最大值,并更新;若不为空,则比较当前下标和栈顶元素的差值.

时间复杂度: O(N)

空间复杂度: O(N)

public int longestValidParentheses(String s) {
int longest=0;
Stack<Integer> stack=new Stack<Integer>();

int left=-1;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')
stack.push(i);
else{
if(stack.isEmpty())
left=i;
else{
stack.pop();
if(stack.isEmpty())
longest=longest>(i-left)?longest:(i-left);
else
longest=longest>(i-stack.peek())?longest:(i-stack.peek());//连续的括号想匹配的长度
}
}
}
return longest;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: