c# - 如何检查括号是否相同

标签 c#

我想检查输入字符串是否包含相同数量的开/关括号。如果是,则打印出 true 否则为 false。我已经写了这段代码但是有一些错误有人可以帮忙吗?

See My Code 如果我输入一个以左括号开头并以右括号结尾的字符串“()”,这就可以正常工作,但是如果我输入“)(”,那么它仍然会打印出 true?。输出应该是:

() = true
(())=true
()) = false
(() = false
)( = false
)(() = false 
etc...

感谢帮助

编辑:

 using System;

public class Program
{
  public  void Main()
 {

    CheckParentheses ("()");
 }

 public void CheckParentheses (string inputParentheses){

 int openParentheses  = 0;
 int closeParentheses = 0;
 for (int i = 0; i < inputParentheses.Length; i++)
 {
   if (inputParentheses[i] == '(') 
    {
        openParentheses++;
    }

     if (inputParentheses[i] == ')') {
        closeParentheses++;
     }


     if (openParentheses == closeParentheses) 

        Console.WriteLine("true");   

  }

 } 

}

最佳答案

您可以检查他们的顺序,而不是计算开/关括号

public void CheckParentheses(string inputParentheses)
{
    // Level counter
    int parenLevel = 0;
    for (int i = 0; i < inputParentheses.Length; i++)
    {
        // Open always good, increment the level
        if (inputParentheses[i] == '(')
            parenLevel++;
        else if (inputParentheses[i] == ')')
            parenLevel--;

        // Closing good, but only if the level doesn't drop under zero
        if (parenLevel < 0)
        {
            Console.WriteLine("false");
            return;
        }
    }
    // At the end of the loop, the level should always be zero
    if(parenLevel != 0)
        Console.WriteLine("false");
    else
        Console.WriteLine("true");
}

关于c# - 如何检查括号是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35259799/

相关文章:

c# - WPF DataGrid 选定的单元格更改为 "The current value of the SelectionUnit property on the parent DataGrid prevents rows from being selected."

c# - 如何从 C# 调用 C .dll?

c# - 获取TreeView所选节点的位置

c# - session 在自定义操作过滤器中不起作用

c# - 用于执行 "Between"的 Linq 表达式

c# - 将 IKVMC 生成的对象序列化为 JSON

c# - 如何通过C#释放句柄?

c# - tempDirectory编译配置

c# - 为 HttpRequestMessage.Properties 定义的字典键 "MS_HttpContext"在哪里?

c# - 通过 REST 从 SharePoint 2013 中的列表中提取数据