这个算法给人的第一感觉是挺简单的,而且类似的还有一个算法是--有效括号。查看括号是不是一一对应的。但是在写的时候还是遇到了挺多的坑的。记录一下。
首先这类问题肯定先想到队列、栈等等。比较之下要使用栈(stack)
大概就是这样的,直接上代码:
public class bracket{
public static int bracketLength(String s){
if (s == null || s.length() == 0){
return 0;
}
// 创建一个空栈
Deque<Integer> stack = new ArrayDeque<Integer>();
// 给栈添加一个基本数据,要不如果第一个就是")"就容易空指针
stack.push(-1);
//System.out.println(stack);
// 定义一个初始长度
int res = 0;
for (int i = 0; i < s.length(); i++) {
// 如果是"(",直接入栈。
if (s.charAt(i) == '(') stack.push(i);
// 如果是")",就需要出栈,然后继续判断一下栈是不是为空了
else {
stack.pop();
// 如果此时栈空了,那么我们就需要将此时的 角标位置放入栈中。
if (stack.isEmpty()) {
stack.push(i);
}
// 如果不是空的,就计算长度。每次都进行比较,只留下来最长的一个数
else {
res = Math.max(res, i - stack.peek());
}
}
}
return res;
}
public static void main(String[] args) {
String s = ")()())";
int i = leetcode1(s);
System.out.println(i);
}
}