Problem with Stack Algorithm

1

I started programming in C # recently and I'm already having some problems ... I took a URI exercise to train and I have an "error" that I do not know how to solve. I've looked for several places and found nothing. Anyway, let's go the situation:

The algorithm resolves parenthesis balancing given any input. I used a file reading with BufferedStream to get the lines I want to work with. However when running with a 20 entries in txt the deal does not go as expected. Entries like ) and () () give an error (that is, they do not output the correct result). I do not know if there is any specific scheme in reading the file because as I said I'm starting in the language.

Follow 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 took the filepath just not to show my directory, but it does exist! Here is an example entry:

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

The most interesting thing is that if you run txt with a single entry, for example just ) , the result is correct.

    
asked by anonymous 22.10.2017 / 06:15

1 answer

0

You need to clear the stack, elements.Clear() , after parsing each line.

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

    elements.Clear();
}
    
22.10.2017 / 14:45