如何检查括号验证

dan*_*kob 6 c# string algorithm

我希望能够得到string并检查它Parentheses是否有效.

例如:

"(ew)[]" - this will be valid.

"(ew[)]" - this will be not valid.
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

public static bool CheckString(string input)
{
    int braceSum = 0, squareSum = 0, parenSum = 0;

    foreach (char c in input)
    {  
        if (c == '{')
            braceSum++;
        if (c == '}')
            braceSum--;
        if (c == '[')
            squareSum++;
        if (c == ']')
            squareSum--;
        if (c == '(')
            parenSum++;
        if (c == ')')
            parenSum--;

        //check for negatives (pair closes before it opens)
        if (braceSum < 0 || squareSum < 0 || parenSum < 0)
            return false;
    }

    return (braceSum == 0 && squareSum == 0 && parenSum == 0);
}
Run Code Online (Sandbox Code Playgroud)

所以在 这两种情况下我的代码都会返回true.为了让程序正常工作,您对我需要添加什么有任何建议吗?

Dmi*_*nko 11

尝试Stack基于经典的验证:

public static bool CheckString(string input) {
  if (string.IsNullOrEmpty(input))
    return true;

  Stack<char> brackets = new Stack<char>();

  foreach (var c in input) {
    if (c == '[' || c == '{' || c == '(')
      brackets.Push(c);
    else if (c == ']' || c == '}' || c == ')') {
      // Too many closing brackets, e.g. (123))
      if (brackets.Count <= 0)
        return false;

      char open = brackets.Pop();

      // Inconsistent brackets, e.g. (123]
      if (c == '}' && open != '{' ||
          c == ')' && open != '(' ||
          c == ']' && open != '[')
        return false;
    }
  }

  // Too many opening brackets, e.g. ((123) 
  if (brackets.Count > 0)
    return false;

  return true;
}
Run Code Online (Sandbox Code Playgroud)

演示:

 string[] tests = new string[] {
    "123",
    "(123)",
    "(1(23)",
    "(12)3)",
    "(ew)[]",
    "(ew[)]",
    "[12(34]56)",
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-10} : {(CheckString(test) ? "Valid" : "Invalid")}"));

  Console.Write(report);
Run Code Online (Sandbox Code Playgroud)

结果:

123        : Valid
(123)      : Valid
(1(23)     : Invalid
(12)3)     : Invalid
(ew)[]     : Valid
(ew[)]     : Invalid
[12(34]56) : Invalid
Run Code Online (Sandbox Code Playgroud)