8

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

 2 years ago
source link: https://blog.51cto.com/u_13321676/5707625
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

精选 原创

灰太狼_cxh 2022-09-23 17:48:38 博主文章分类:leetcode ©著作权

文章标签 子串 字符串 代码实现 文章分类 Java 编程语言 阅读数189

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

输入:s = "(()"

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

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

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

输入:s = ""

代码实现:

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;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK