给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"输出: 2解释: 最长有效括号子串为 "()"示例 2:
输入: ")()())"输出: 4解释: 最长有效括号子串为 "()()"
算法:我们用两个变量分别记录左右括号的长度,先从左到右走一趟,当左括号小于右括号时归零,若中途两者相等,更新括号长度;然后再从右往左走一趟,规则与第一次相反。
class Solution {
public:
int longestValidParentheses(
string s) {
int l=
0,r=
0,res=
0;
for(
int i=
0;i<s.size();i++
){
if(s[i]==
'(')l++
;
else r++
;
if(l==r)res=max(res,
2*
l);
else if(r>l)l=r=
0;
}
l=r=
0;
for(
int i=s.size()-
1;i>=
0;i--
){
if(s[i]==
'(')l++
;
else r++
;
if(l==r)res=max(res,
2*
l);
else if(l>r)l=r=
0;
}
return res;
}
};
转载于:https://www.cnblogs.com/programyang/p/11179133.html
相关资源:各显卡算力对照表!