Skip to content

Commit 391d4ff

Browse files
aQuaaQua
aQua
authored and
aQua
committed
finish Problem 32
我的答案,不是最快的,但我觉得是最清晰的思路
1 parent d5cb513 commit 391d4ff

File tree

3 files changed

+42
-19
lines changed

3 files changed

+42
-19
lines changed

Algorithms/0032.longest-valid-parentheses/README.md

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,20 @@ For `"(()"`, the longest valid parentheses substring is `"()"`, which has length
88
Another example is `")()())"`, where the longest valid parentheses substring is `"()()"`, which has length = 4.
99

1010
## 解题思路
11-
12-
11+
1.记录每个符号的状态,`(`一律对应于`0``)`如果能够和前面的配上对,就记录为`2`,否则,记录为`0`
12+
```
13+
) ( ( ) ( ) ) ) ( ( ( ( ( ) ) ) ) (
14+
```
15+
形成记录
16+
```
17+
0 0 0 2 0 2 2 0 0 0 0 0 0 2 2 2 2 0
18+
```
19+
20+
2.从左往右检查record,如果record[i]==2,record[j]==0,且record[j+1:i]中没有0,则record[i]=1,record[j]=1,那么,上面的record就变成了
21+
```
22+
0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0
23+
```
24+
3.统计record中,最多的连续为1的次数,就是结果。
1325
## 总结
1426

15-
27+
根据记录统计,往往是最清晰的

Algorithms/0032.longest-valid-parentheses/longest-valid-parentheses.go

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,38 @@
11
package Problem0032
22

33
func longestValidParentheses(s string) int {
4-
var i, j, max, temp int
4+
var left, max, temp int
55
record := make([]int, len(s))
6-
lens := len(s)
76

8-
for i < lens {
9-
for i < lens-1 && !(s[i] == '(' && s[i+1] == ')') {
10-
i++
7+
// 统计Record
8+
for i, b := range s {
9+
if b == '(' {
10+
left++
11+
} else if left > 0 {
12+
left--
13+
record[i] = 2
1114
}
12-
j = i + 1
13-
for i >= 0 && s[i] == '(' && j < lens && s[j] == ')' {
15+
}
16+
17+
// 修改record
18+
for i := 0; i < len(record); i++ {
19+
if record[i] == 2 {
20+
j := i - 1
21+
for record[j] != 0 {
22+
j--
23+
}
1424
record[i], record[j] = 1, 1
15-
i--
16-
j++
1725
}
18-
19-
i = j
2026
}
2127

28+
// 统计结果
2229
for _, r := range record {
2330
if r == 0 {
2431
temp = 0
25-
} else {
26-
temp++
32+
continue
2733
}
2834

35+
temp++
2936
if temp > max {
3037
max = temp
3138
}

Algorithms/0032.longest-valid-parentheses/longest-valid-parentheses_test.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,21 @@ func Test_Problem0032(t *testing.T) {
2828
ast := assert.New(t)
2929

3030
qs := []question{
31-
3231
question{
33-
para{"(()())"},
34-
ans{6},
32+
para{")(()()))((((())))("},
33+
ans{8},
3534
},
3635

3736
question{
3837
para{"()(()"},
3938
ans{2},
4039
},
4140

41+
question{
42+
para{"(()())"},
43+
ans{6},
44+
},
45+
4246
question{
4347
para{"(()"},
4448
ans{2},

0 commit comments

Comments
 (0)