-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path191121-1.cpp
62 lines (58 loc) · 1.53 KB
/
191121-1.cpp
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
// https://leetcode-cn.com/problems/longest-valid-parentheses/
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> stack;
for (int i = 0; s[i]; ++i) {
if (s[i] == '(') {
stack.push_back(i);
} else {
if (!stack.empty()) {
int j = stack.back();
stack.pop_back();
s[i] = s[j] = ' ';
}
}
}
int start = -1;
int longest = 0;
for (int i = 0; ; ++i) {
if (s[i] == ' ') {
if (start < 0) {
start = i;
}
} else {
if (start >= 0) {
int size = i - start;
if (size > longest) {
longest = size;
}
}
start = -1;
if (s[i] == '\0') break;
}
}
return longest;
}
};
int main()
{
Solution s;
printf("%d\n", s.longestValidParentheses("(()")); // answer: 2
printf("%d\n", s.longestValidParentheses(")()())")); // answer: 4
printf("%d\n", s.longestValidParentheses("")); // answer: 0
printf("%d\n", s.longestValidParentheses(")")); // answer: 0
printf("%d\n", s.longestValidParentheses("(")); // answer: 0
printf("%d\n", s.longestValidParentheses(")(")); // answer: 0
printf("%d\n", s.longestValidParentheses("))")); // answer: 0
printf("%d\n", s.longestValidParentheses("))(")); // answer: 0
printf("%d\n", s.longestValidParentheses("()")); // answer: 2
printf("%d\n", s.longestValidParentheses("())")); // answer: 2
printf("%d\n", s.longestValidParentheses(")()")); // answer: 2
printf("%d\n", s.longestValidParentheses(")()(")); // answer: 2
return 0;
}