-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32.longest-valid-parentheses.cpp
More file actions
69 lines (60 loc) · 1.59 KB
/
32.longest-valid-parentheses.cpp
File metadata and controls
69 lines (60 loc) · 1.59 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
/**
* 32. Longest Valid Parentheses
*
* Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
*
* Example 1:
* Input: "(()"
* Output: 2
* Explanation: The longest valid parentheses substring is "()"
*
* Example 2:
* Input: ")()())"
* Output: 4
* Explanation: The longest valid parentheses substring is "()()"
*/
#include "testharness.h"
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> open_pos;
// far_open_pos[i] record farest open parenthes such than
// substr betweent far_open_pos[i] and i is a valid parenthes string.
vector<int> far_open_pos(s.size(), -1);
int max = 0;
for (size_t i = 0; i < s.size(); i++) {
if (s[i] == '(') {
open_pos.push(i);
} else if (s[i] == ')' && !open_pos.empty()) {
int top = open_pos.top();
open_pos.pop();
if (top > 1 && far_open_pos[top-1] != -1) {
far_open_pos[i] = far_open_pos[top-1];
} else {
far_open_pos[i] = top;
}
int len = i - far_open_pos[i] + 1;
if (max < len) {
max = len;
}
}
}
return max;
}
};
TEST(Solution, test) {
std::string str = "(()";
ASSERT_EQ(2, longestValidParentheses(str));
}
TEST(Solution, test2) {
std::string str = ")()())";
ASSERT_EQ(4, longestValidParentheses(str));
}
TEST(Solution, test3) {
std::string str = "()(())";
ASSERT_EQ(6, longestValidParentheses(str));
}
TEST(Solution, test4) {
std::string str = "(";
ASSERT_EQ(0, longestValidParentheses(str));
}