题解 | #最长的括号子串#
最长的括号子串
https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return int整型
*/
public int longestValidParentheses (String s) {
// write code here
if (s.length() <= 1) return 0;
Stack<Integer> stack = new Stack<>();
int res = 0;
int start = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
if (stack.empty()) {
start = i;
} else {
stack.pop();
int l = stack.empty() ? start : stack.peek();
res = Math.max(res, i - l);
}
}
}
return res;
}
}
