Skip to content

Commit c5e8b6b

Browse files
author
Shuo
committedApr 20, 2020
A: Longest Valid Parentheses
1 parent 8eb508f commit c5e8b6b

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed
 

‎internal/leetcode/problems_status.go

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ var problemStatus = map[int]bool{
2727
26: true,
2828
27: true,
2929
28: true,
30+
32: true,
3031
35: true,
3132
36: true,
3233
38: true,
Original file line numberDiff line numberDiff line change
@@ -1 +1,26 @@
11
package problem32
2+
3+
func longestValidParentheses(s string) int {
4+
ans, l := 0, len(s)
5+
dp := make([]int, l)
6+
for i, c := range s {
7+
if i == 0 || c == '(' {
8+
continue
9+
}
10+
if s[i-1] == '(' {
11+
dp[i] = 2
12+
if i > 1 {
13+
dp[i] = dp[i-2] + 2
14+
}
15+
} else if i > dp[i-1] && s[i-1-dp[i-1]] == '(' {
16+
dp[i] = dp[i-1] + 2
17+
if i-1 > dp[i-1] {
18+
dp[i] += dp[i-2-dp[i-1]]
19+
}
20+
}
21+
if dp[i] > ans {
22+
ans = dp[i]
23+
}
24+
}
25+
return ans
26+
}
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package problem32
2+
3+
import "testing"
4+
5+
type testType struct {
6+
in string
7+
want int
8+
}
9+
10+
func TestLongestValidParentheses(t *testing.T) {
11+
tests := [...]testType{
12+
{
13+
in: "(()",
14+
want: 2,
15+
},
16+
{
17+
in: ")()())",
18+
want: 4,
19+
},
20+
{
21+
in: ")()())(())()(",
22+
want: 6,
23+
},
24+
{
25+
in: "()(())",
26+
want: 6,
27+
},
28+
}
29+
for _, tt := range tests {
30+
got := longestValidParentheses(tt.in)
31+
if got != tt.want {
32+
t.Fatalf("in: %v, got: %v, want: %v", tt.in, got, tt.want)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)
Please sign in to comment.