1 结题思想
题目会给出一定的“((())))”等的括号对,问你说最长的有效括号对是多长?
这道题,需要用Stack,并且不能单纯的统计(或),且出栈,其大致有如下的规则:
1、遇到(要压栈当前位置
2、遇到)时,如果还有(在栈中,那么计算此个括号对的长度
3、如果)时,如果没有(在栈中,那么检查上一次匹配开始的位置 last,
4、如果)时,没有(在栈中,那么last就需要重置,这点和3相关
总结:
需要记录上一次匹配成功的位置这是重点,重点是Stack空了之后的处理
2 原题
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.
3 AC解
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
char chars[]=s.toCharArray();
int max=0;
int last=0; //上一个成功匹配的位置
int n=s.length();
int m=n-1;
for(int i=0;i<n;i++){
if(chars[i]=='(')
stack.push(i);
else{
if(stack.isEmpty()) //需要弹出栈(的时候,却没有数字,所以这个)符号做了一个截断
last=i+1;
else{
stack.pop();
if(stack.empty()) //为空的时候才能和之前的上一个最开始的位置匹配,不然只能和当前最远的括号比
max=Math.max(max,i-last+1);
else
max=Math.max(max,i-stack.peek());
}
}
}
return max;
}
}