/
03. CheckBrackets.cs
49 lines (42 loc) · 1.19 KB
/
03. CheckBrackets.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Write a program to check if in a given expression the brackets are put correctly.
// Example of correct expression: ((a+b)/5-d).
// Example of incorrect expression: )(a+b)).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class CheckBrackets
{
static void Main()
{
Console.WriteLine("Please, insert an expression");
string input = Console.ReadLine();
Stack<char> brackets = new Stack<char>();
brackets.Push('(');
while (brackets.Count != 0)
{
brackets.Pop();
foreach (var element in input)
{
if (element == '(')
{
brackets.Push(element);
}
else if (element == ')')
{
if (brackets.Count == 0)
{
Console.WriteLine("Incorrect expression!");
return;
}
brackets.Pop();
}
}
}
if (brackets.Count == 0)
{
Console.WriteLine("Correct expression!");
}
}
}