题目:
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。所以,在求相应的长度的时候,需要记录"("出现的位置,然后计算匹配的长度,如果匹配的长度大于之前记录的长度,那么久更新,否则就不变。
public class Solution
{
public static int longestValidParentheses(String s)
{
if (s == null || s.length() == 0)
return 0;
int len = s.length(), maxLen = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for (int i = 0; i < len; i++)
{
if (s.charAt(i) == '(')
stack.push(i);
else
{
if (stack.size() > 1 && s.charAt(stack.peek()) == '(')
{
stack.pop();
System.out.println(stack.peek());
maxLen = Integer.max(i - stack.peek(), maxLen);
System.out.println(maxLen);
}
else
stack.push(i);
}
}
return maxLen;
}
}