C#检查表达式是否有效

时间:2016-04-21 03:29:49

标签: c# syntax stack arithmetic-expressions

表达式:

  

"(a [i] + { - 1} *(8-9))"

应该返回true,因为写这样的语法是有效的。每个左侧支架在正确的位置靠近,所有支架都处于合法位置。
我尝试通过一个堆栈来做这个,我知道我错在哪里,但我想知道解决这个问题的相关方法。 谢谢!
我可怜的错误代码:

            string expression = "( a[i]+{-1}*(8-9) ) ";
        Stack<char> expStack = new Stack<char>();
        List<char> rightBracketsHolder = new List<char>();
        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '{')
            {
                expStack.Push('}');
                Console.Write("}" + " ");
            }
            else if (expression[i] == '(')
            {
                expStack.Push(')');
                Console.Write(")" + " ");
            }
            else if (expression[i] == '[')
            {
                expStack.Push(']');
                Console.Write("]" + " ");
            }
        }
        Console.WriteLine();
        for (int i = 0; i < expression.Length; i++)
        {
            if (expression[i] == '}')
            {
                rightBracketsHolder.Add('}');
                Console.Write(expression[i] + " ");
            }
            else if (expression[i] == ')')
            {
                rightBracketsHolder.Add(')');
                Console.Write(expression[i] + " ");
            }
            else if (expression[i] == ']')
            {
                rightBracketsHolder.Add(']');
                Console.Write(expression[i] + " ");
            }
        }
        Console.WriteLine();
        bool stackResult = checkValidity(expStack, rightBracketsHolder);
        if (stackResult)
            Console.WriteLine("Expression is Valid.");
        else
            Console.WriteLine("\nExpression is not valid.");
        Console.ReadKey();
    }

    private static bool checkValidity(Stack<char> expStack, List<char> leftBracketsHolder)
    {
        Console.WriteLine();
        int length = leftBracketsHolder.Count;
        for (int i = 0; i < length; i++)
        {
            if (expStack.Peek().ToString().Contains(leftBracketsHolder.ToString()))
            {
                leftBracketsHolder.Remove(expStack.Peek());
                expStack.Pop();

            }
        }
        if (expStack.Count == 0 && leftBracketsHolder.Count ==0)
        {
            return true;
        }
        return false;
    }
}

2 个答案:

答案 0 :(得分:1)

此代码将解决您的目的 -

static void Main(string[] args)
    {
        bool error = false;
        var str = "( a[i]+{-1}*(8-9) )";
        Stack<char> stack = new Stack<char>();
        foreach (var item in str.ToCharArray())
        {
            if (item == '(' || item == '{' || item == '[')
            {
                stack.Push(item);
            }
            else if(item == ')' || item == '}' || item == ']')
            {
                if (stack.Peek() != GetComplementBracket(item))
                {
                    error = true;
                    break;
                }
            }
        }

        if (error)
            Console.WriteLine("Incorrect brackets");
        else
            Console.WriteLine("Brackets are fine");
        Console.ReadLine();
    }

    private static char GetComplementBracket(char item)
    {
        switch (item)
        {
            case ')':
                return '(';
            case '}':
                return '{';
            case ']':
                return '[';
            default:
                return ' ';
        }
    }

答案 1 :(得分:0)

您需要在关闭时弹出堆栈。请尝试以下代码。它将在堆栈上推动一个打开的大括号/括号/括号,然后它将通过相应的关闭从堆栈中弹出。否则它无效。如果遇到关闭时堆栈上没有打开,则无效。如果您在完成后有任何额外的打开,则无效。

我还使用了switch语句而不是if语句只是因为我认为它更容易阅读。

using System;
using System.Collections.Generic;

public class Program
{
   public static void Main()
   {
      string expression = "( a[i]+{-1}*(8-9) ) ";
      bool stackResult = checkValidity(expression);

      if (stackResult)
         Console.WriteLine("Expression is Valid.");
      else
         Console.WriteLine("\nExpression is not valid.");
   }

   private static bool checkValidity(string expression)
   {
      Stack<char> openStack = new Stack<char>();
      foreach (char c in expression)
      {
         switch (c)
         {
            case '{':
            case '(':
            case '[':
               openStack.Push(c);
               break;
            case '}':
               if (openStack.Count == 0 || openStack.Peek() != '{')
               {
                  return false;
               }
               openStack.Pop();       
               break;
            case ')':
               if (openStack.Count == 0 || openStack.Peek() != '(')
               {
                  return false;
               }
               openStack.Pop();       
               break;
            case ']':
               if (openStack.Count == 0 || openStack.Peek() != '[')
               {
                  return false;
               }
               openStack.Pop();       
               break;
            default:
               break;
         }
      }
      return openStack.Count == 0;
   }
}