C#检查表达式是否括号有效
C# checking if expression is brackets valid
表达式:
"( a[i]+{-1}*(8-9) )"
应该return 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;
}
}
此代码将解决您的问题 -
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 ' ';
}
}
您需要在关闭时从堆栈中弹出东西。试试下面的代码。它将在堆栈上压入一个打开的brace/bracket/parenthesis,然后第一件事就是通过相应的关闭将其从堆栈中弹出。否则无效。如果遇到close时栈上没有opens,则无效。如果您在完成时有任何额外的打开,则它是无效的。
我还使用了 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;
}
}
表达式:
"( a[i]+{-1}*(8-9) )"
应该return 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;
}
}
此代码将解决您的问题 -
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 ' ';
}
}
您需要在关闭时从堆栈中弹出东西。试试下面的代码。它将在堆栈上压入一个打开的brace/bracket/parenthesis,然后第一件事就是通过相应的关闭将其从堆栈中弹出。否则无效。如果遇到close时栈上没有opens,则无效。如果您在完成时有任何额外的打开,则它是无效的。
我还使用了 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;
}
}