Search code examples
c#algorithmrecursionparentheses

C# Controlling balanced parenthesis to recursive


I am trying to write a function to control if the parenthesis included in a stringare balanced or not.

I have written the following function:

public bool IsBalanced(string input)
{
    //last condition, gets out
    if (string.IsNullOrEmpty(input)) return true;

    int numOpen = 0;
    bool opened = false;
    foreach (char c in input)
    {
        if (char.ToUpperInvariant(c) =='(')
        {
            opened = true;
            numOpen+=1;
        }
        if (char.ToUpperInvariant(c) == ')')
        {
            if (opened)
            {
                numOpen-=1;
                opened = numOpen > 0;
            }
            else
                return false; //incorrect position parentheses, closes but not opened
        }
    }

    return numOpen == 0;
}

I wanted to change it to a recursive function, but have not been able to do so. Could anyone give a hint how to do it?


Solution

  • The basic idea is to take a variant (numOpen in this case) as an argument. Here is my code:

    public bool IsBalancedRec(string input, int numOpen = 0)
    {
        if (numOpen < 0)
            return false;
        if (string.IsNullOrEmpty(input))
            return numOpen == 0;
    
        char c = input[0];
        string rest = input.Substring(1);
    
        if (c == '(')
            return IsBalancedRec(rest, numOpen + 1);
        else if (c == ')')
            return IsBalancedRec(rest, numOpen - 1);
        else
            return IsBalancedRec(rest, numOpen);
    }
    

    And call this like IsBalancedRec("so(m(eth)ing)").