暴力解法
每当我们遇到一个 \text{‘(’}‘(’ ,我们把它放在栈顶。对于遇到的每个 \text{‘)’}‘)’ ,我们从栈中弹出一个 \text{‘(’}‘(’ ,如果栈顶没有 \text{‘(’}‘(’,或者遍历完整个子字符串后栈中仍然有元素,那么该子字符串是无效的。这种方法中,我们对每个偶数长度的子字符串都进行判断,并保存目前为止找到的最长的有效子字符串的长度。
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push('(');
} else if (!stack.empty() && stack.peek() == '(') {
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
public int longestValidParentheses(String s) {
int maxlen = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 2; j <= s.length(); j+=2) {
if (isValid(s.substring(i, j))) {
maxlen = Math.max(maxlen, j - i);
}
}
}
return maxlen;
}
}
栈解法
与找到每个可能的子字符串后再判断它的有效性不同,我们可以用栈在遍历给定字符串的过程中去判断到目前为止扫描的子字符串的有效性,同时能的都最长有效字符串的长度。我们首先将 -1−1 放入栈顶。
对于遇到的每个 \text{‘(’}‘(’ ,我们将它的下标放入栈中。
对于遇到的每个 \text{‘)’}‘)’ ,我们弹出栈顶的元素并将当前元素的下标与弹出元素下标作差,得出当前有效括号字符串的长度。通过这种方法,我们继续计算有效子字符串的长度,并最终返回最长有效子字符串的长度。
转自LeetCode官方题解
https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode/
public static int longestValidParentheses(String s) {
int maxlen=0;
Stack<Integer> stack=new Stack<>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i)=='(')
{
stack.push(i);
}
else {
stack.pop();
//(((
if (stack.empty())
{
stack.push(i);
}
else
{
maxlen=Math.max(maxlen,i-stack.peek());
}
}
}
return maxlen;
}