wasnt nate

Interview Question: Validate Parantheses Align

This is should be an easy one; given an input string determine if there is a matching close parentheses for every open parentheses.

For example; the string “abc(def)(j((k)))lm()” should return true.
However; the string “def(()xyz” would return false.
Did you remember the case “sdf())abc)” should also return false?

public static bool IsValidParantheseExpression(string input)
{
    var opened = 0;
    for (var i = 0; i < input.Length; i++)
    {
        if (input[i] == '(')
        {
            opened++;
            continue;
        }
        else if (input[i] == ')')
        {
            opened--;
            if (opened < 0)
                return false;
        }
    }

    return opened == 0;
}

Leave a Reply