File tree Expand file tree Collapse file tree 1 file changed +90
-0
lines changed
LeetCode/all/LeetCode/all Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @lc app=leetcode.cn id=32 lang=golang
3+ *
4+ * [32] 最长有效括号
5+ *
6+ * https://leetcode-cn.com/problems/longest-valid-parentheses/description/
7+ *
8+ * algorithms
9+ * Hard (35.20%)
10+ * Likes: 1378
11+ * Dislikes: 0
12+ * Total Accepted: 168.1K
13+ * Total Submissions: 476.1K
14+ * Testcase Example: '"(()"'
15+ *
16+ * 给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
17+ *
18+ *
19+ *
20+ *
21+ *
22+ * 示例 1:
23+ *
24+ *
25+ * 输入:s = "(()"
26+ * 输出:2
27+ * 解释:最长有效括号子串是 "()"
28+ *
29+ *
30+ * 示例 2:
31+ *
32+ *
33+ * 输入:s = ")()())"
34+ * 输出:4
35+ * 解释:最长有效括号子串是 "()()"
36+ *
37+ *
38+ * 示例 3:
39+ *
40+ *
41+ * 输入:s = ""
42+ * 输出:0
43+ *
44+ *
45+ *
46+ *
47+ * 提示:
48+ *
49+ *
50+ * 0
51+ * s[i] 为 '(' 或 ')'
52+ *
53+ *
54+ *
55+ *
56+ */
57+
58+ // @lc code=start
59+ func longestValidParentheses (s string ) int {
60+ maxAns := 0
61+ dp := make ([]int , len (s ))
62+ for i := 1 ; i < len (s ); i ++ {
63+ if s [i ] == ')' {
64+ if s [i - 1 ] == '(' {
65+ if i >= 2 {
66+ dp [i ] = dp [i - 2 ] + 2
67+ } else {
68+ dp [i ] = 2
69+ }
70+ } else if i - dp [i - 1 ] > 0 && s [i - dp [i - 1 ] - 1 ] == '(' {
71+ if i - dp [i - 1 ] >= 2 {
72+ dp [i ] = dp [i - 1 ] + dp [i - dp [i - 1 ] - 2 ] + 2
73+ } else {
74+ dp [i ] = dp [i - 1 ] + 2
75+ }
76+ }
77+ maxAns = max (maxAns , dp [i ])
78+ }
79+ }
80+ return maxAns
81+ }
82+
83+ func max (x ,y int ) int {
84+ if x > y {
85+ return x
86+ }
87+ return y
88+ }
89+ // @lc code=end
90+
You can’t perform that action at this time.
0 commit comments