Problem with Stack Algorithm

Asked

Viewed 222 times

1

I started programming in C# recently and I’m already having some problems... I took a URI exercise to train and I have a "mistake" that I don’t know how to solve. Anyway, here’s the situation:

The algorithm solves balancing parentheses given any input. I used a file reading with Bufferedstream to get the lines I want to work with. But when running with 20 entries in txt the business does not go as expected. Entries like ) and ()() fail (that is, the correct result does not come out). I do not know if there is any specific scheme in reading the file because as I said I am starting in language.

Follows the code:

public static void Main()
{
    Stack<char> elements = new Stack<char>();
    string input;
    FileStream fs = File.Open(filepath,FileMode.Open);
    BufferedStream bs = new BufferedStream(fs);
    StreamReader sr = new StreamReader(bs);
    while ((input = sr.ReadLine()) != null)
    {

        foreach (char c in input)
        {
            if (c.Equals('(')) elements.Push(c);
            if (c.Equals(')'))
            {
                if (elements.Count != 0) elements.Pop();
                else elements.Push(c);
            }
        }
        if (elements.Count == 0) Console.WriteLine("correct "+ input);
        else Console.WriteLine("incorrect "+ input);
    }
    Console.Read();
}

*I removed the filepath only to not show my directory, but it exists! Follow an example entry:

(
)
()
)(
()(
())
(()
)()
()()
())(
)(()
(())
))((
)()(
)(()
(()())

The most interesting thing is that when running with txt with a single input, for example, only ), the result is correct.

1 answer

0


You need to clean the pile, elements.Clear(), after analyzing each line.

while ((input = sr.ReadLine()) != null)
{
    foreach (char c in input)
    {
        ...
    }
    ...

    elements.Clear();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.