题目地址
中文:https://leetcode-cn.com/problems/longest-valid-parentheses/
英文:https://leetcode.com/problems/longest-valid-parentheses/
题目描述
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".
Example 2:
Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".
Example 3:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 3 * 10^4
s[i] is ‘(’, or ‘)’.
思路
遍历每个子串,设置两个变量left和right,记录左右括号的个数,如果出现left<right的情况,说明这段有问题,left==right的时候说明是一段合理的子串,如果长度更大的话就更新。
题解
class Solution {
public int longestValidParentheses(String s) {
int start = 0;
int maxLen=0;
int left = 0;//left和right记录左右括号的数量
int right=0;
//如果有left小于right的情况,说明出错
for(int j=0;j<s.length();++j) {
start = j;
left=0;
right=0;
for (int i = j; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
if (left == right && i - start +1> maxLen) maxLen = i - start+1;
if (left - right < 0) {
left = 0;
right = 0;
start = i+1;
}
}
}
}
return maxLen;
}
}