Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 186d384

Browse files
author
Shuo
authored
Merge pull request #784 from openset/develop
A: Longest Valid Parentheses
2 parents 973fa7f + df037eb commit 186d384

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

‎internal/leetcode/problems_status.go‎

Lines changed: 1 addition & 0 deletions
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,
Lines changed: 25 additions & 0 deletions
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]
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+
}
Lines changed: 34 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /