-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
88 lines (81 loc) · 2 KB
/
Copy pathmain.cpp
File metadata and controls
88 lines (81 loc) · 2 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Source: https://leetcode.com/problems/longest-valid-parentheses
// Title: Longest Valid Parentheses
// Difficulty: Hard
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Given a string containing just the characters `'('` and `')'`, return the length of the longest valid (well-formed) parentheses substring.
//
// **Example 1:**
//
// ```
// Input: s = "(()"
// Output: 2
// Explanation: The longest valid parentheses substring is "()".
// ```
//
// **Example 2:**
//
// ```
// Input: s = ")()())"
// Output: 4
// Explanation: The longest valid parentheses substring is "()()".
// ```
//
// **Example 3:**
//
// ```
// Input: s = ""
// Output: 0
// ```
//
// **Constraints:**
//
// - `0 <= s.length <= 3 * 10^4`
// - `s[i]` is `'('`, or `')'`.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <stack>
#include <string>
using namespace std;
// Two pointer
//
// Scan from left to right.
// Whenever there are more right paren than left paren,
// we shrink the substring from the left.
//
// We also do the same again from right to left.
class Solution {
public:
int longestValidParentheses(const string& s) {
const int n = s.size();
// Left to right
int ans = 0;
int i = 0; // [i, j]
int diff = 0; // left - right
for (int j = 0; j < n; ++j) {
diff += (s[j] == '(') ? 1 : -1;
if (diff == 0) {
ans = max(ans, j - i + 1);
}
while (diff < 0) {
diff -= (s[i] == '(') ? 1 : -1;
++i;
}
}
// Right to left
i = n - 1; // [i, j]
diff = 0; // right - left
for (int j = n - 1; j >= 0; --j) {
diff += (s[j] == ')') ? 1 : -1;
if (diff == 0) {
ans = max(ans, i - j + 1);
}
while (diff < 0) {
diff -= (s[i] == ')') ? 1 : -1;
--i;
}
}
return ans;
}
};