您的位置:首页 > 编程语言 > Java开发

[Leetcode] Longest Valid Parentheses (Java)

2013-12-29 12:02 489 查看
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.

括号匹配的问题,开始就自作聪明的想到“(”为1,“)”为-1,给一个模式串pattern[s.length()];若pattern[i-1]>=0;则pattern[i]=pattern[i-1]+1或pattern[i-1]-1;如果pattern[i]>0则需要向前找匹配,复杂度为O(n2),代码看着还很乱,觉得一定是有不对的地方。。。

看到"()"括号匹配,首先应该想到栈的嘛。。换了个思路果然代码清晰了。。

import java.util.Stack;

public class LongestValidParentheses {
public int longestValidParentheses(String s) {
if(s.length()<1)
return 0;
int max = 0;
int last = -1;
Stack<Integer> stack = new Stack<Integer>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')
stack.add(i);
else {
if(stack.isEmpty())
last = i;
else {
stack.pop();
if(stack.isEmpty())
max = Math.max(max, i-last);
else {
max = Math.max(max, i-stack.peek());
}
}
}
}
return max;
}
public static void main(String[] args) {
String s = "(()()";
System.out.println(new LongestValidParentheses().longestValidParentheses(s));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: