您的位置:首页 > 其它

leetcode做题总结,题目Longest Valid Parentheses 2012/02/29

2014-07-30 23:43 435 查看
找出最长匹配括号,我的方法是用栈储存,把"("入栈,遇到")"和栈顶匹配,匹配成功则出栈如果无法匹配就入栈。这样全部运行一遍后栈里就剩下没匹配的了,而这些元素之间就是各个能匹配的括号的队列。我的方法是用一个新的栈储存栈里每个元素的位置信息,这样用最后剩余的元素的位置信息相减就是各个括号队列的长度。

注意:这道题在OJ系统上遇到了点问题,一个是代码中的curr=m1-0;我之前写的是curr=m1-0+1;系统未报错,这里不能用0,因为0也是位置量,所以应该是-1。第二个问题是,注释掉本没用的s1.push(a.length);同样的代码在本地输入"()"输出2而在线输出0,我查了下,在线S1栈里会多出来一个0,不知道为什么。 所以OJ上AC了也不能保证代码的绝对正确啊。

public int longestValidParentheses(String s) {
if(s.equals(""))return 0;
int max=0;
int curr=0;
String[] a = s.split("");
Stack<Integer> s1= new Stack<Integer>();
Stack<String> s2= new Stack<String>();
for(int r=0;r<a.length;r++){
if(a[r].equals("(")){
s1.push(r);
s2.push(a[r]);
}else{
if(s1.isEmpty()){
s1.push(r);
s2.push(a[r]);
}else{
if(s2.peek().equals("(")){
s1.pop();
s2.pop();
}else{
s1.push(r);
s2.push(a[r]);
}
}
}
}
s1.push(a.length);       //见我的注释

if(s1.isEmpty()){
max= s.length();
}else{
int m1=s1.pop();
int m2;
while(!s1.isEmpty()){
m2=s1.pop();
curr=m1-m2-1;
if(curr>max)max=curr;
m1=m2;
}
curr=m1-0;    //
if(curr>max)max=curr;
}
return max;

}


Update 2015/08/21: 上面的方法很复杂,下面是一个简单地算法,这个题是求最长子串,不是简单的求配对数量。

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