#yyds干货盘点# LeetCode 热题 HOT 100:最长有效括号

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#yyds干货盘点# LeetCode 热题 HOT 100:最长有效括号相关的知识,希望对你有一定的参考价值。

题目:

给你一个只包含 ( 和 ) 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

 

示例 1:

输入:s = "(()"

输出:2

解释:最长有效括号子串是 "()"

示例 2:

输入:s = ")()())"

输出:4

解释:最长有效括号子串是 "()()"

示例 3:

输入:s = ""

输出:0

代码实现:

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;

以上是关于#yyds干货盘点# LeetCode 热题 HOT 100:最长有效括号的主要内容,如果未能解决你的问题,请参考以下文章

#yyds干货盘点# LeetCode 热题 HOT 100:最长有效括号

#yyds干货盘点# LeetCode 热题 HOT 100:对称二叉树

#yyds干货盘点# LeetCode 热题 HOT 100:旋转图像

#yyds干货盘点# LeetCode 热题 HOT 100:单词搜索

#yyds干货盘点# LeetCode 热题 HOT 100:组合总和

#yyds干货盘点# LeetCode 热题 HOT 100:接雨水