Problem: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Solution:
public static int LongestValidParentheses(string s)
{
Stack<int> stack = new Stack<int>();
stack.Push(-1);
int result = 0;
for(int i = 0; i < s.Length; ++i)
{
if (s[i] == '(')
{
stack.Push(i);
}
else
{
stack.Pop();
if (stack.Count > 0)
{
result = Math.Max(result, i - stack.Peek());
}
else
{
stack.Push(i);
}
}
}
return result;
}
No comments:
Post a Comment