Tests
static void Main()
{
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded(""));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("("));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded(")"));
Console.WriteLine("Expected: {0}, Is: {1}", true, IsSurrounded("()"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(()"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("())"));
Console.WriteLine("Expected: {0}, Is: {1}", true, IsSurrounded("(.(..)..(..)..)"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(..)..(..)"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(..)..(..)..)"));
Console.WriteLine("Expected: {0}, Is: {1}", false, IsSurrounded("(.(..)..(..)"));
}
Method
Very fast
- No stack
- No loop through entire string
If the first opening parenthesis has its closing counterpart, then the result can't be true. Same thing about last closing parenthesis.
static bool IsSurrounded(string text)
{
if (text.Length < 2 || text.First() != '(' || text.Last() != ')')
return false;
for (var i = 1; i < text.Length - 1; i++)
{
if (text[i] == ')')
return false;
if (text[i] == '(')
break;
}
for (var i = text.Length - 2; i > 0; i--)
{
if (text[i] == '(')
return false;
if (text[i] == ')')
break;
}
return true;
}
Limitations
Should be not used when there are more recursive parentheses such as ((..)) + ((..))