Balance or not expression

a string consisisting of characters < and >. The string is balanced if each < always appesrs before a corresponing > and more over each < and > act as a unique pairof symbols To balance a string any > characters can b ereplace with < >. Given an express and a maximum number of replacements, determine whether the string can be balanced:

example: expression =['<<>>','<>',<><>','>>','><><'] maxReplacements =[0,1,2,2,2,2]

 public static List<int> balancedOrNot(List<string> expressions, List<int> maxReplacements)
{
    List<int> result = new List<int>();
    for (int i = 0; i < expressions.Count; i++)
    {
        string expression = expressions[i];
        int replacements = maxReplacements[i];
        Stack<char> stack = new Stack<char>();
        bool isBalanced=true;
        foreach (char c in expression)
        {
            if (c == '<')
            {
                stack.Push(c);
            }
            else if (c == '>')
            {
                if (stack.Count > 0)
                {
                    stack.Pop();
                }
                else if (replacements > 0)
                {
                    replacements--;
                }
                else
                {
                isBalanced=false;
                    result.Add(0);
                    break;
                }
            }
        }
        if(isBalanced)
        {
            if (stack.Count == 0)
            {
                result.Add(1);
            }
            else
            {
                result.Add(0);
            }
        }
    }
    return result;
}

Last updated