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.
解题思路:
这道题跟之前的一道题比较像,所以我的做法就是用栈的方式,如果当前的是')'而栈顶是'(',就对栈顶进行pop操作。反之将当前的char放入栈中。
这道题比较麻烦的就是,要来计算最大子串。不能单纯的看最后栈的存储量来决定,而是要看栈中存储的char在字符串中的位置。所以我就进行了相应的修改。用一个栈来存储char,一个栈来储存对应的index。(其实也可以只用一个存储index的栈,或者弄一个map什么的)。在每次要将char存入到栈中时,判断当前Index减去栈顶index是否大于1,大于1证明有子串存在,进行最大子串更新。
public class Solution {
public int longestValidParentheses(String s) {
int result = 0;
int len1 = 0;
int len2 = 0;
Stack<Character> sstack = new Stack<Character>();
Stack<Integer> istack = new Stack<Integer>();
for(int i = 0;i<s.length();i++)
{
char sub = s.charAt(i);
//匹配,进行pop操作
if(!sstack.isEmpty() && sstack.peek() == '(' && sub == ')')
{
sstack.pop();
istack.pop();
}
else
{
sstack.push(sub);
//更新最长子串
if(istack.isEmpty())
result = Math.max(result, i);
else if(i-istack.peek()-1>0)
result = Math.max(result, i-istack.peek()-1);
istack.push(i);
}
}
if(!istack.isEmpty())
result = Math.max(s.length()-istack.peek()-1,result);
else
result = s.length();
return result;
}
}