-
Notifications
You must be signed in to change notification settings - Fork 115
/
032-LongestValidParentheses.cs
56 lines (52 loc) · 1.52 KB
/
032-LongestValidParentheses.cs
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
//-----------------------------------------------------------------------------
// Runtime: 124ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _032_LongestValidParentheses
{
public int LongestValidParentheses(string s)
{
int i, maxLen = 0, lastError = -1, depth = 0;
for (i = 0; i < s.Length; i++)
{
if (s[i] == '(') { depth++; }
else
{
depth--;
if (depth < 0)
{
depth = 0;
lastError = i;
}
else if (depth == 0)
{
maxLen = maxLen < i - lastError ? i - lastError : maxLen;
}
}
}
lastError = s.Length;
depth = 0;
for (i = s.Length - 1; i >= 0; i--)
{
if (s[i] == ')') { depth++; }
else
{
depth--;
if (depth < 0)
{
depth = 0;
lastError = i;
}
else if (depth == 0)
{
maxLen = maxLen < lastError - i ? lastError - i : maxLen;
}
}
}
return maxLen;
}
}
}