32:最长有效括号

This commit is contained in:
轩辕龙儿 2022-03-19 22:08:17 +08:00
parent 070a9b14d4
commit d64a073254
2 changed files with 135 additions and 0 deletions

View File

@ -0,0 +1,95 @@
//给你一个只包含 '(' ')' 的字符串找出最长有效格式正确且连续括号子串的长度
//
//
//
//
//
// 示例 1
//
//
//输入s = "(()"
//输出2
//解释最长有效括号子串是 "()"
//
//
// 示例 2
//
//
//输入s = ")()())"
//输出4
//解释最长有效括号子串是 "()()"
//
//
// 示例 3
//
//
//输入s = ""
//输出0
//
//
//
//
// 提示
//
//
// 0 <= s.length <= 3 * 10
// s[i] '(' ')'
//
//
//
// Related Topics 字符串 动态规划 👍 1706 👎 0
package leetcode.editor.cn;
import javafx.util.Pair;
import java.util.*;
//32:最长有效括号
public class LongestValidParentheses {
public static void main(String[] args) {
Solution solution = new LongestValidParentheses().new Solution();
solution.longestValidParentheses("(()");
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int longestValidParentheses(String s) {
Stack<Pair<String, Integer>> stack = new Stack<>();
while (s.startsWith(")")) {
s = s.substring(1);
}
while (s.endsWith("(")) {
s = s.substring(0, s.length() - 1);
}
List<Integer> list = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.add(new Pair<>("(", i));
} else if (!stack.isEmpty() && "(".equals(stack.peek().getKey())) {
list.add(stack.pop().getValue());
list.add(i);
} else {
stack.add(new Pair<>(")", i));
}
}
if (list.size() == 0) {
return 0;
}
Collections.sort(list);
int max = 0;
int count = 1;
for (int i = 1; i < list.size(); i++) {
if (list.get(i) == list.get(i - 1) + 1) {
count++;
} else {
max = Math.max(max, count);
count = 1;
}
}
return Math.max(max, count);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p>给你一个只包含 <code>'('</code> 和 <code>')'</code> 的字符串,找出最长有效(格式正确且连续)括号子串的长度。</p>
<p> </p>
<div class="original__bRMd">
<div>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>s = "(()"
<strong>输出:</strong>2
<strong>解释:</strong>最长有效括号子串是 "()"
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>s = ")()())"
<strong>输出:</strong>4
<strong>解释:</strong>最长有效括号子串是 "()()"
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>s = ""
<strong>输出:</strong>0
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>0 <= s.length <= 3 * 10<sup>4</sup></code></li>
<li><code>s[i]</code><code>'('</code><code>')'</code></li>
</ul>
</div>
</div>
<div><div>Related Topics</div><div><li></li><li>字符串</li><li>动态规划</li></div></div><br><div><li>👍 1706</li><li>👎 0</li></div>