-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMatchingBrackets.cs
More file actions
34 lines (30 loc) · 902 Bytes
/
MatchingBrackets.cs
File metadata and controls
34 lines (30 loc) · 902 Bytes
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CSharp.DS.Algo.Stack
{
public class MatchingBrackets
{
public bool IsValid(string s)
{
var bracketStack = new Stack<char>();
var bracketsMap = new Dictionary<char, char>
{
{ '(', ')' },
{ '[', ']' },
{ '{', '}' }
};
for (int i = 0; i < s.Length; i++)
{
// Console.WriteLine(s[i]);
if (bracketsMap.TryGetValue(s[i], out var expected)) // opening bracket
bracketStack.Push(expected);
else // closing bracket
if (!bracketStack.Any() || bracketStack.Pop() != s[i])
return false;
}
return !bracketStack.Any();
}
}
}