题目:
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.
分析:
给定一个字符串只包含字符'(' ')',找到最长的有效长度(形成)括号内的子串。
“(()”,最长有效括号子串是“()”,其长度= 2。另一个例子是“)()())”,其中最长的子串是“有
效的括号()()”,其长度= 4。
本题使用栈stack,不是用来存左右括号的。是来存左括号的index。遍历s。遇到'(',将index压进ss,如果遇
到')',则弹出一个'('如果ss是空,说明这是一个无法匹配的')',记录下start。start里面存放的其实是最后一
个无法匹配的')'。为啥要保存这个值呢?主要是为了计算后面完整的表达式的长度。可以这样理解: “所有无法匹
配的')'”的index其实都是各个group的分界点。
代码:
import java.util.*;
public class Solution {
public int longestValidParentheses(String s) {
int k= s.length();
if (k<2) return 0;
int result = 0;
int start = -1;
Stack<Integer> ss = new Stack<Integer>();
for(int i = 0;i<k;i++){
if(s.charAt(i)=='('){
ss.push(i);
}else{
if(ss.isEmpty()) start = i;
else{
ss.pop();
if(!ss.isEmpty())
result = Math.max(i-ss.peek(),result);
else
result = Math.max(i-start,result);
}
}
}
return result;
}
}