【问题标题】:Testing if Parenthesis are balanced, (a{[]b({})}c)[] returns false, but should be true测试括号是否平衡, (a{[]b({})}c)[] 返回 false,但应该为 true
【发布时间】:2026-01-06 07:20:06
【问题描述】:

这段代码的重点是测试每组字符串中的括号是否平衡。有 12 个测试必须全部通过,目前,我有 11 个在工作,但是最后一个不会工作。 目前,我有三个静态布尔值,它们正在阐明什么归类为括号,以及它们是否匹配。

 private static bool IsOpeningParenthesis(char c)
        {
            return c == '(' || c == '[' || c == '{';
        }

private static bool IsClosingParenthesis(char c)
        {
            return c == ')' || c == ']' || c == '}';
        }

private static bool Matches(char a, char b)
        {
            return (a == '(' && b == ')') || (a == '[' && b == ']') ||
                (a == '{' && b == '}');
        }

下面,我有一个 bool 来实际检查它们是否匹配,这就是我的错误所在。

public static bool IsBalanced(string s)
        {
            Stack<char> myStack = new Stack<char>();

            foreach (char c in s)
            {
                if (IsOpeningParenthesis(c))
                {
                    myStack.Push(c);
                }
                if (IsClosingParenthesis(c))
                {
                    if (myStack.Count == 0) //takes care of closing parenthesis before adding char d
                    {
                        return false;
                    }
                    char d =  myStack.Pop();
                    if (c == d)
                    {
                        return true;
                    }
                    else
                    {
                        myStack.Push(d);
                        return false;
                    }   
                }
            }
            if(myStack.Count == 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

最后一点代码,这些都是正在检查的所有测试。我目前正在努力解决测试编号 9 / TestFLongMatch。

public void TestFLongMatch()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("(a{[]b({})}c)[]"), Is.True);
        }

以下是包含所有测试的完整文件

/* ParenthesisMatcherTests.cs
 * Author: Rod Howell
 */
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ksu.Cis300.Parentheses;

namespace Ksu.Cis300.Parentheses.Tests
{
    /// <summary>
    /// A unit test class for the class library Ksu.Cis300.Parentheses.
    /// </summary>
    [TestFixture]
    public class ParenthesisMatcherTests
    {
        /// <summary>
        /// Checks the empty string, which is balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestAEmptyString()
        {
            Assert.That(ParenthesisMatcher.IsBalanced(""), Is.True);
        }

        /// <summary>
        /// Checks the string "abcdefg", which is balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestBNoParentheses()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("abcdefg"), Is.True);
        }

        /// <summary>
        /// Checks the string "[", which is not balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestCOpeningParenthesis()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("["), Is.False);
        }

        /// <summary>
        /// Checks the string ")", which is not balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestDClosingParenthesis()
        {
            Assert.That(ParenthesisMatcher.IsBalanced(")"), Is.False);
        }

        /// <summary>
        /// Tests the string "{{}", which is not balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestEMissingClose()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("{{}"), Is.False);
        }

        /// <summary>
        /// Tests the string "[[]", which is not balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestEExtraClose()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("[]]"), Is.False);
        }

        /// <summary>
        /// Tests the string "[}", which is not balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestEMismatch()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("[}"), Is.False);
        }

        /// <summary>
        /// Tests the string "[}]", which is not balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestEMismatch2()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("[}]"), Is.False);
        }

        /// <summary>
        /// Tests the string "(a{[]b({})}c)[]", which is balanced.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestFLongMatch()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("(a{[]b({})}c)[]"), Is.True);
        }

        /// <summary>
        /// Tests the string "(a{[]b({})}c)[](", whose last parenthesis is not matched.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestFLongMissingClose()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("(a{[]b({})}c)[]("), Is.False);
        }

        /// <summary>
        /// Tests the string "(a{[]b({})}c)[]())", whose last parenthesis is not matched.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestFLongExtraClose()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("(a{[]b({})}c)[]())"), Is.False);
        }

        /// <summary>
        /// Tests the string "(a{[]b({})}c}[]", whose first character is paired with the last '}', and
        /// hence is mismatched.
        /// </summary>
        [Test, Timeout(1000)]
        public void TestFLongMismatch()
        {
            Assert.That(ParenthesisMatcher.IsBalanced("(a{[]b({})}c}[]"), Is.False);
        }
    }
}

当我通过调试器运行特定测试时,代码将运行并遍历字符串,直到它到达第一个右括号。 一旦右括号开始起作用,并且从测试中删除了左括号和右括号,程序就停止返回false。但是,它应该继续通过字符串并返回 True。老实说,我在这段代码上迷失了,因为与这个非常相似的其他匹配字符串通过了,并且在第一个结束点之后没有退出。

任何有关如何解决此问题的建议将不胜感激。如果需要任何其他帮助,请告诉我,我试图包含尽可能多的信息。

【问题讨论】:

  • 您的代码中至少存在一个错误,如果您测试最简单的正面案例,应该更容易识别:Assert.That(ParenthesisMatcher.IsBalanced("[]"), Is.True);
  • 运行该测试仅显示我的代码正在运行,但是,除了Assert.That(ParenthesisMatcher.IsBalanced("(a{[]b({})}c)[]"), Is.True); 之外,每个测试都显示自己运行正常
  • 当你说平衡时,你的意思是开括号和右括号的数量相等,还是说它们不能相互重叠。例如,这是否平衡:( { ) }?
  • 不,那些不平衡。 a b c 之类的字母不会影响括号是否平衡。比如[]是平衡的,[)是不平衡的

标签: c# foreach parentheses


【解决方案1】:

通过查看代码,我认为问题在于您的IsBalanced 方法在遇到右括号时立即返回false

在您的代码中,当遇到右括号时,这些是选项:

  1. 堆栈上没有项目:return false
  2. 堆栈中的第一项是相同的右括号(这是不可能的):return true
  3. return false

要解决此问题,您可能需要使用 Matches 方法来检查右括号是否与从堆栈中弹出的字符匹配:

public static bool IsBalanced(string input)
{
    var stack = new Stack<char>();

    foreach (var chr in input)
    {
        if (IsOpeningParenthesis(chr))
        {
            stack.Push(chr);
        }
        else if (IsClosingParenthesis(chr))
        {
            if (stack.Count == 0) return false;
            if (!Matches(stack.Pop(), chr)) return false;
        }
    }

    return stack.Count == 0;
}

【讨论】:

  • 我的评论是为了让 OP 意识到 if (c == d) 永远不会是真的 :)