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.
确实挺难的
一开始的想法是这样的 一个有效的字符串肯定是以”(“开头的 那么就从每个”(“开始 遇到”(“就push进stack
遇到”)” 分两种情况
1.stack如果是空的 说明没有对应的”(“ 目前为止的字符串无效 长度归零
2.如果stack不为空就pop一个”(“出来 长度+2
过程中求最大长度 比如输入是 “()((()))”
我们用i代表扫描的位置
当i=1时 len=2
i=2,3,4时 因为没有对应的”)” len=2
i=5,6,7 len分别对应4,6,8
代码如下
public int longestValidParentheses(String s) {
Stack<Character> stack = new Stack<>();
int local = 0, len = 0;
for (char c : s.toCharArray()) {
switch (c) {
case '(':
stack.push(c);
break;
case ')':
if (!stack.isEmpty()) {
stack.pop();
local+=2;
len = Math.max(len, local);
} else {
local = 0;
}
break;
}
}
return len;
}
乍一看没什么问题 但是当输入是”()((()”时呢
返回结果是4 而不是2
因为我只判断了”)”无效的情况 长度会归零
没有判断”("无效的情况 也就是”(“没有对应的”)”的情况 也应该长度归零
而且也没有必要用stack 用left记录”(“的个数 用right记录”)”的个数 当left == right len+=2*left就可以了
那该怎么修改呢 再从右到左扫描一遍
public class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, maxlength = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * right);
} else if (right >= left) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * left);
} else if (left >= right) {
left = right = 0;
}
}
return maxlength;
}
}