-
Notifications
You must be signed in to change notification settings - Fork 2
/
Stack example in Balanced parentheses.cs
80 lines (80 loc) · 2.13 KB
/
Stack example in Balanced parentheses.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// solve the problem How to know if this bracket's is balanced ex ({1+9}*2)+[5-2] ... to know must sure if last added bracket { has his closing }
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
class Solution
{
static void Main(String[] args)
{
string s = Console.ReadLine();
if (Balanced(s))
{
Console.WriteLine("Expression is balanced");
}
else
{
Console.WriteLine("Expression is Not balanced");
}
}
public static bool Balanced(string exp)
{
Stack open_Brackets = new Stack(); // stack to store open brackets ordering
for (int i = 0; i < exp.Length; i++)
{
if (exp[i]=='('|| exp[i] == '{' || exp[i] == '[')
{
open_Brackets.Push(exp[i]);
}
else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if (open_Brackets.IsEmpty())
{
return false;
}
else if (Pair(Convert.ToChar(open_Brackets.Top()),exp[i]) == false)
{
return false;
}
open_Brackets.Pop();
}
}
if (open_Brackets.IsEmpty())
{
return true;
}
return false;
}
public static bool Pair(char open , char close)
{
if (open =='(' && close ==')'){return true;}
else if (open == '{' && close == '}'){return true;}
else if (open == '[' && close == ']'){return true;}
return false;
}
}
class Stack
{
int[] arr = new int[100];
int top = -1; // this make arr empty
public void Push(int val)
{
if (top==99){return; } // to make sure that array not empty
top++;
arr[top] = val;
}
public void Pop()
{
if (IsEmpty()){return;}
top--;
}
public int Top()
{
if (IsEmpty()){return -1;} // to make sure that array not empty
return arr[top];
}
public bool IsEmpty()
{
return top == -1 ? true : false;
}
}