简体   繁体   English

测试括号是否平衡,(a{[]b({})}c)[] 返回 false,但应该为 true

[英]Testing if Parenthesis are balanced, (a{[]b({})}c)[] returns false, but should be true

The point of this code is to test if the parenthesis in each set of strings are balanced.这段代码的重点是测试每组字符串中的括号是否平衡。 there are 12 tests that must all pass, currently, i have 11 of them working, however this last one will not work.有 12 个测试必须全部通过,目前,我有 11 个在工作,但是最后一个不起作用。 currently, i have three static bools that are clarifying what classifies as a parenthesis, and if they match or not.目前,我有三个静态布尔值,它们阐明了括号的分类,以及它们是否匹配。

 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 == '}');
        }

below, i have the bool which actually checks if they are matching or not, this is where my error lies.下面,我有实际检查它们是否匹配的 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;
            }

        }

final bit of code, these are all the tests that are being checked.最后一点代码,这些是正在检查的所有测试。 I am currently struggling with Test number 9 / TestFLongMatch.我目前正在为测试编号 9 / TestFLongMatch 苦苦挣扎。

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

below is the full file with all the tests以下是包含所有测试的完整文件

/* 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);
        }
    }
}

when i ran the specific test through a debugger, the code would work and run through the string until it reached until it reached the first closing bracket.当我通过调试器运行特定测试时,代码将工作并运行字符串,直到它到达第一个右括号为止。 once the closing bracket came into play, and the opening and closing brackets were removed from the test, and the program stopped returning false.一旦结束括号起作用,并且开始和结束括号从测试中删除,程序停止返回false。 However it is supposed to continue on through the string and return True.但是,它应该继续通过字符串并返回 True。 Im honestly lost on this code as other matching strings very similar to this one passed, and did not quit after the first closing point.老实说,我迷失在这段代码中,因为其他与此非常相似的匹配字符串通过了,并且在第一个结束点后没有退出。

Any advice on how to tackle this problem would be greatly appreciated.任何关于如何解决这个问题的建议将不胜感激。 If anything else is needed to help with this please let me know, i tried to include as much info as possible.如果需要其他任何帮助,请告诉我,我尝试包含尽可能多的信息。

From looking at the code, I think the problem is that your IsBalanced method returns false right away as soon as it runs into a closing parenthesis.从查看代码来看,我认为问题在于您的IsBalanced方法在IsBalanced右括号时立即返回false

In your code, when a closing parenthesis is encountered, these are the options:在您的代码中,当遇到右括号时,有以下选项:

  1. There are no items on the stack: return false堆栈上没有项目: return false
  2. The first item on the stack is the same closing parenthesis (which is impossible): return true堆栈上的第一项是同一个右括号(这是不可能的): return true
  3. return false

To fix this, you might want to make use of your Matches method to check if the closing parenthesis is a match for the character popped from the stack:要解决此问题,您可能需要使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM