-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cs
40 lines (39 loc) · 1.16 KB
/
Solution.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
using System.Collections.Generic;
public class Solution {
public int LongestValidParentheses(string s) {
var result = 0;
var baseCount = 0;
var stack = new Stack<int>();
foreach (var ch in s)
{
switch (ch)
{
case '(':
stack.Push(1);
break;
case ')':
if (stack.Count > 0)
{
var count = stack.Pop() + 1;
if (stack.Count > 0)
{
count += stack.Pop();
stack.Push(count);
if (count - 1 > result) result = count - 1;
}
else
{
baseCount += count;
if (baseCount > result) result = baseCount;
}
}
else
{
baseCount = 0;
}
break;
}
}
return result;
}
}