题解 | #最长的括号子串#
最长的括号子串
https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
int longestValidParentheses(string s) {
// write code here
/*
) ( ) ( ) )
L 0 1 1 2 2
R 0 0 1 1 2
从左往右和从右往左看,什么样的情况下是合法的
从左往右的时候,左括号可以比右括号多,否则清零;
*/
int maxi = 0;
int left = 0, right = 0;
for(int i=0;i<s.length();i++)
{
if(s[i]==')')
{
if(right>=left)
{
right = 0;
left = 0;
}
else {
right++;
}
}
else
{
left++;
}
if(left==right)
{
if(left>maxi)
maxi=left;
}
}
left=0;
right =0;
for(int i=s.length()-1;i>0;i--)
{
if(s[i]=='(')
{
if(left>=right)
{
right = 0;
left = 0;
}
else {
left++;
}
}
else
{
right++;
}
if(left==right)
{
if(left>maxi)
maxi=left;
}
}
return maxi*2;
}
};

深信服公司福利 802人发布