思路:用栈保存左括号(
遇到(就直接压入栈中。
遇到):要用一个变量保存第一个(的下标位置firstLeftPos
如果当前栈为空,则更新firstLeftPos,然后忽略这个)。
如果栈非空,则弹栈,取出匹配的(。如果弹栈后的栈非空则根据当前)的下标和栈顶元素计算长度;如果弹栈后的栈为空,则更具当前)的下标和firstLeftPos计算长度。
package Level4;
import java.util.Stack;
/**
Longest Valid Parentheses
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.
*/
public class S32 {
public static void main(String[] args) {
System.out.println(longestValidParentheses("(())"));
System.out.println(longestValidParentheses(")("));
System.out.println(longestValidParentheses("()()"));
System.out.println(longestValidParentheses("(()"));
}
public static int longestValidParentheses(String s) {
if(s.length() < 2){
return 0;
}
Stack<Pair> stack = new Stack<Pair>();
int curPos = 0;
int firstLeftPos = 0; // 存放第一个 ( 的下标位置
int max = 0;
while(curPos < s.length()){
char c = s.charAt(curPos);
if(c == '('){
stack.push(new Pair(c, curPos));
}else{ // c == ')'
if(!stack.isEmpty()){ // 栈非空
stack.pop(); // 把对应的 ( 弹出
if(!stack.isEmpty()){ // 弹栈后,栈内仍有元素
max = Math.max(max, curPos-stack.peek().index);
}else{ // 弹栈后,栈空了
max = Math.max(max, curPos-firstLeftPos+1);
}
}else{ // 栈空,又遇到 ), 更新都一个(的下标位置
firstLeftPos = curPos + 1;
}
}
curPos++; // 更新当前遍历string的下标位置
}
return max;
}
// 构建一个Pair,同时存放字符和其对应下标
public static class Pair{
char c;
int index;
public Pair(char c_, int index_){
c = c_;
index = index_;
}
}
}