C# Nesting
static int Nesting(string s)
{
if (string.IsNullOrEmpty(s))
{
return 1;
}
var stack = new Stack<char>();
foreach (var v in s)
{
if (v == ')')
{
if (stack.Count == 0 || stack.Pop() != '(')
{
return 0;
}
}
else
{
stack.Push(v);
}
}
return stack.Count == 0 ? 1 : 0;
}
This treats the string like a balance counter: open parentheses add one, closing ones remove one.