Repository navigation
Expand file tree
/
Copy path0032_v2.cpp
More file actions
74 lines (63 loc) · 1.51 KB
/
Copy path0032_v2.cpp
File metadata and controls
74 lines (63 loc) · 1.51 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
68
69
70
71
72
73
74
// LeetCode-32:Longest Valid Parentheses(最长有效括号) -- Hard
// https://blog.csdn.net/Koala_Tree/article/details/81385559
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <stack>
#include <vector>
// #include <utility>
using namespace std;
static const auto _ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int longestValidParentheses(string s) {
if (s.empty()) return 0;
int maxlen=0;
int t[s.size()+1];
int ptr = -1;
memset(t, -1, sizeof(t));
t[0] = -2;
for (int i=0; i<s.size(); ++i) {
if (s[i]=='(') {
t[i+1] = ptr;
ptr = i;
} else {
ptr = t[ptr+1];
if (ptr == -2) {
if (maxlen >= s.size()-1-i)
break;
ptr = i;
t[ptr+1] = -2;
} else {
if (maxlen<i-ptr)
maxlen = i-ptr;
}
}
}
return maxlen;
}
};
int main() {
string sin, din;
vector<string> vs;
vector<int> vd;
ifstream fp;
fp.open("0032.txt");
while (getline(fp, sin, '\n')) {
vs.push_back(sin);
getline(fp, din, '\n');
vd.push_back(stoi(din.c_str(),NULL,10));
}
fp.close();
for (int i=0; i<vs.size(); ++i) {
int n = longestValidParentheses(vs[i]);
printf("%d\t%d\t%d\t%d\n", n==vd[i], 2*i+1, vd[i], n);
}
return 0;
}