forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BalancedParenthesesChecker.cs
90 lines (81 loc) · 2.92 KB
/
BalancedParenthesesChecker.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
using System;
using System.Collections.Generic;
namespace Algorithms.Stack
{
/// <summary>
/// It checks if an expression has matching and balanced parentheses.
/// @author Mohit Singh. <a href="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/mohit-gogitter">mohit-gogitter</a>
/// </summary>
public class BalancedParenthesesChecker
{
private static readonly Dictionary<char, char> ParenthesesMap = new Dictionary<char, char>
{
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
};
/// <summary>
/// Determines if a given string expression containing brackets is balanced.
/// A string is considered balanced if all opening brackets have corresponding closing brackets
/// in the correct order. The supported brackets are '()', '{}', and '[]'.
/// </summary>
/// <param name="expression">
/// The input string expression containing the brackets to check for balance.
/// </param>
/// <returns>
/// <c>true</c> if the brackets in the expression are balanced; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the input expression contains invalid characters or is null/empty.
/// Only '(', ')', '{', '}', '[', ']' characters are allowed.
/// </exception>
public bool IsBalanced(string expression)
{
if (string.IsNullOrEmpty(expression))
{
throw new ArgumentException("The input expression cannot be null or empty.");
}
Stack<char> stack = new Stack<char>();
foreach (char c in expression)
{
if (IsOpeningParenthesis(c))
{
stack.Push(c);
}
else if (IsClosingParenthesis(c))
{
if (!IsBalancedClosing(stack, c))
{
return false;
}
}
else
{
throw new ArgumentException($"Invalid character '{c}' found in the expression.");
}
}
return stack.Count == 0;
}
private static bool IsOpeningParenthesis(char c)
{
return c == '(' || c == '{' || c == '[';
}
private static bool IsClosingParenthesis(char c)
{
return c == ')' || c == '}' || c == ']';
}
private static bool IsBalancedClosing(Stack<char> stack, char close)
{
if (stack.Count == 0)
{
return false;
}
char open = stack.Pop();
return IsMatchingPair(open, close);
}
private static bool IsMatchingPair(char open, char close)
{
return ParenthesesMap.ContainsKey(open) && ParenthesesMap[open] == close;
}
}
}