-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathValidParentheses.cs
More file actions
54 lines (49 loc) · 1.45 KB
/
ValidParentheses.cs
File metadata and controls
54 lines (49 loc) · 1.45 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
using System;
using System.Collections.Generic;
namespace Algorithms.Strings
{
/// <summary>
/// This is a class for checking if the parentheses is valid.
/// A valid parentheses should have opening brace and closing brace.
/// </summary>
public static class ValidParentheses
{
/// <summary>
/// Function to check if the parentheses is valid.
/// </summary>
/// <param name="parentheses">String to be checked.</param>
public static bool IsValidParentheses(string parentheses)
{
if (parentheses.Length % 2 != 0)
{
return false;
}
Dictionary<char, char> bracketPairs = new Dictionary<char, char>
{
{ ')', '(' },
{ '}', '{' },
{ ']', '[' },
};
Stack<char> stack = new Stack<char>();
foreach (char c in parentheses)
{
if (bracketPairs.ContainsValue(c))
{
stack.Push(c);
}
else if (bracketPairs.ContainsKey(c))
{
if (stack.Count == 0 || stack.Pop() != bracketPairs[c])
{
return false;
}
}
else
{
return false;
}
}
return stack.Count == 0;
}
}
}