-
Notifications
You must be signed in to change notification settings - Fork 0
/
Checkforbalancedparenthesesinanexpression.cs
97 lines (81 loc) · 2.29 KB
/
Checkforbalancedparenthesesinanexpression.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
public class Prgram
{
public static void Main(string[] args)
{
List<string> brs = new List<string>();
brs.Add("{}[]()");
brs.Add("{[}]");
var results = areBracesBalancedArray(brs.ToArra());
foreach(var r in results)
{
Console.WriteLine(r);
}
}
// Complete the braces function below.
static string[] areBracesBalancedArray(string[] values) {
List<string> result = new List<string>();
foreach(string item in values)
{
if(areBracesBalanced(item))
{
result.Add("YES");
}
else{
result.Add("NO");
}
}
return result.ToArray();
}
static bool areBracesBalanced(string s)
{
char[] chars = s.ToArray();
Stack<Char> brstack = new Stack<Char>(); //LIFO
// only add opening braces to stack, and for each others, pop stack and check for matches
for(int i =0; i < chars.Length; i++)
{
if(chars[i] == '{' || chars[i] == '[' || chars[i] == '(') //start adding opening braces to stack
{
brstack.Push(chars[i]);
}
if(chars[i] == '}' || chars[i] == ']' || chars[i] == ')')
{
if(brstack.Count == 0) //first element check no elements in the stack, so no matching
{
return false;
}
else if(!checkForMatchingPair(brstack.Pop(), chars[i])) //else check for matching paits, if true continue, if false break
{
return false;
}
}
}
if(brstack.Count == 0) // will be 0 if all the pairs matched so return true
{
return true;
}
else
{
return false;
}
}
static bool checkForMatchingPair(char c1, char c2)
{
//check for '{', '[', ')'
if(c1 == '{' && c2 == '}')
{
return true;
}
else if(c1 == '[' && c2 == ']' )
{
return true;
}
else if(c1 == '(' && c2 == ')')
{
return true;
}
else
{
return false;
}
}
}