-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32-LongestValidParentheses.py
More file actions
67 lines (62 loc) · 1.62 KB
/
32-LongestValidParentheses.py
File metadata and controls
67 lines (62 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Python3
class Solution:
def longestValidParentheses(self, s: str) -> int:
res = 0
stk = list()
mark = [0]*len(s)
for i in range(len(s)):
if s[i] == '(':
stk.append(i)
elif s[i] == ')':
if not stk:
mark[i] = 1
else:
stk.pop()
while stk:
mark[stk[-1]] = 1
stk.pop()
cnt = 0
for j in range(len(s)):
if mark[j] == 1:
cnt = 0
else:
cnt += 1
res = max(cnt, res)
return res
# C++
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
vector<bool> mark(s.length());
for (int i = 0; i < mark.size(); i++) {
mark[i] = 0;
}
int left = 0, len = 0, ans = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(') {
stk.push(i);
} else {
if (stk.empty()) { // 标记多余的右括号
mark[i] = 1;
} else {
stk.pop();
}
}
}
while (!stk.empty()) { // 标记多余的左括号
mark[stk.top()] = 1;
stk.pop();
}
// 寻找最长的连续的0(标记)的长度
for (int i = 0; i < s.length(); i++) {
if (mark[i]) {
len = 0;
continue;
}
len++;
ans = max(ans, len);
}
return ans;
}
};