-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatchedBracketStringValidator.cs
More file actions
59 lines (51 loc) · 1.72 KB
/
Copy pathMatchedBracketStringValidator.cs
File metadata and controls
59 lines (51 loc) · 1.72 KB
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
using System.Collections.Generic;
using System.Linq;
namespace code_challenge
{
public class MatchedBracketStringValidator
{
private static readonly Dictionary<char, char> BracketPairs = new()
{
{ '[', ']' },
{ '(', ')' },
{ '{', '}' }
};
private static readonly List<char> OpenBrackets = BracketPairs.Keys.ToList();
private static readonly List<char> CloseBrackets = BracketPairs.Values.ToList();
public string ErrorMessage { get; private set; } = string.Empty;
public bool IsValid(string input)
{
var openBracketStack = new Stack<char>();
foreach (var charItem in input)
{
if (OpenBrackets.Contains(charItem))
{
openBracketStack.Push(charItem);
}
if (!openBracketStack.Any() || !CloseBrackets.Contains(charItem))
{
continue;
}
if (AreBracketsMatching(openBracketStack.Peek(), charItem))
{
openBracketStack.Pop();
}
else
{
ErrorMessage = "Wrong closing order";
return false;
}
}
if (openBracketStack.Any())
{
ErrorMessage = $"Missing closing '{BracketPairs[openBracketStack.Peek()]}'";
return false;
}
return true;
}
private static bool AreBracketsMatching(char openBracket, char closeBracket)
{
return BracketPairs[openBracket] == closeBracket;
}
}
}